题目描述
如题,给出一个有向图,请输出从某一点出发到所有点的最短路径长度。
输入输出格式
输入格式:
第一行包含三个整数N、M、S,分别表示点的个数、有向边的个数、出发点的编号。
接下来M行每行包含三个整数Fi、Gi、Wi,分别表示第i条有向边的出发点、目标点和长度。
输出格式:
一行,包含N个用空格分隔的整数,其中第i个整数表示从点S出发到点i的最短路径长度(若S=i则最短路径长度为0,若从点S无法到达点i,则最短路径长度为2147483647)
输入输出样例
输入样例#1:
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
输出样例#1:
0 2 4 3
说明
时空限制:1000ms,128M
数据规模:
对于20%的数据:N<=5,M<=15
对于40%的数据:N<=100,M<=10000
对于70%的数据:N<=1000,M<=100000
对于100%的数据:N<=10000,M<=500000
分析:spfa模版题。
代码:
const
MaxE=10002;
MaxV=500001;
type
rec=record
x,y,w,next:longint;
end;
var
n,m,c,i,x,y,w,o:longint;
g:array [-1..Maxv] of rec;
ls:array [-1..Maxe] of longint;
v,d,list,sum:array [-1..maxe] of longint;
procedure spfa(first:longint);
var
head,tail,t,i:longint;
begin
tail:=1; head:=0;
list[1]:=first;
for i:=1 to n do
d[i]:=maxlongint;
d[first]:=0;
v[first]:=1;
while tail<>head do
begin
head:=head mod maxe+1;
t:=ls[list[head]];
while t>0 do
with g[t] do
begin
if d[x]+wthen
begin
d[y]:=d[x]+w;
if v[y]=0 then
begin
v[y]:=1;
tail:=tail mod maxe+1;
list[tail]:=y;
end;
end;
t:=next;
end;
v[list[head]]:=0;
end;
end;
procedure add(x,y,w:longint);
begin
inc(o);
g[o].x:=x;
g[o].y:=y;
g[o].w:=w;
g[o].next:=ls[x];
ls[x]:=o;
end;
begin
read(n,m,c);
for i:=1 to m do
begin
read(x,y,w);
add(x,y,w);
end;
spfa(c);
for i:=1 to n do
write(d[i],' ');
end.