- 问答
- 2014-07-18 14:28:16 @
题目描述
给定M条边,N个点的带权无向图
求1到N的最短路
N<=100000
M<=500000
输入
第一行:N,M
接下来M行3个正整数:ai,bi,ci 表示ai,bi之间有一条长度为ci的路
ci<=1000
输出
一个整数,表示1到N的最短距离
样例输入
4 4
1 2 1
2 3 1
3 4 1
2 4 1
样例输出
2
提示
注意图中可能有重边和自环,数据保证1到N有路径相连
用SPFA写一下
5 条评论
-
乖孩子 LV 3 @ 2014-10-29 18:36:28
百度呗
-
2014-08-06 18:16:11@
orz
-
2014-08-05 19:38:58@
Orz
-
2014-08-05 19:15:31@
蒟蒻乱打的
-
2014-08-05 19:15:22@
var
graph:array[1..100,1..100]of longint;
n,m:longint;
dist:array[1..100]of longint;
procedure init;
var
i,j,a,b:longint;
begin
read(n,m);
for i:=1 to m do
begin
read(a,b);
read(graph[a,b]);
end;
for i:=2 to n do
dist[i]:=maxlongint;
dist[1]:=0;
end;
procedure spfa;
var
q:array[1..100]of longint;
inq:array[1..100]of boolean;
front,tail,i,x:longint;
begin
fillchar(q,sizeof(q),0);
fillchar(inq,sizeof(inq),false);
front:=1;
tail:=1;
q[1]:=1;
while tail>=front do
begin
x:=q[front];
inc(front);
inq[x]:=false;
for i:=1 to n do
if (graph[x,i]>0)and(dist[i]>dist[x]+graph[x,i]) then
begin
dist[i]:=dist[x]+graph[x,i];
if not inq[i] then
begin
inq[i]:=true;
inc(tail);
q[tail]:=i;
end;
end;
end;
end;
procedure print;
var
i:longint;
begin
for i:=2 to n do
write(dist[i],' ');
end;
begin
init;
spfa;
print;
end.
- 1