题目
给出一个N个顶点M条边的无向无权图,顶点编号为1~N。问从顶点1开始,到其他每个点的最短路有几条。
题解
spfa跑一遍,用链表储存
千万要记得,是无向图!,所以每条边都要储存储存两次,正反各一次。
时间复杂度O(VE)
代码
const
max=2000000;
type
arr=record
x,y,ne:longint;
end;
var
n,m,i,j:longint;
d,c:array[1..max]of longint;
a:array[1..max*2]of arr;
ls:array[1..max]of longint;
v:array[1..max*2] of longint;
state:array[1..max*2]of longint;
procedure spfa;
var
head,tail,t,x,y,ne:longint;
begin
head:=0;tail:=1;
v[1]:=1;
state[1]:=1;
while head<=tail do
begin
inc(head);
t:=ls[state[head]];
while t>0 do
begin
x:=a[t].x;y:=a[t].y;ne:=a[t].ne;
if d[x]+1<d[y] then
begin
d[y]:=d[x]+1;
if v[y]=0 then
begin
inc(tail);
v[y]:=1;
state[tail]:=y;
c[y]:=c[x] mod 100003;
end;
end else
if d[x]+1=d[y] then
begin
c[y]:=(c[y]+c[x]) mod 100003;
end;
t:=ne;
end;
v[state[head]]:=0;
end;
end;
begin
readln(n,m);
fillchar(d,sizeof(d),$7f);
for i:=1 to m do
begin
inc(j);
readln(a[j].x,a[j].y);
a[j].ne:=ls[a[j].x];
ls[a[j].x]:=j;
inc(j);
a[j].x:=a[j-1].y;a[j].y:=a[j-1].x;
a[j].ne:=ls[a[j].x];
ls[a[j].x]:=j;
end;
d[1]:=0;
c[1]:=1;
spfa;
for i:=1 to n do
writeln(c[i]);
end.