您的位置:首页 > 其它

洛谷 P1144 最短路计数

2017-03-07 17:59 357 查看
题目

题解

代码

题目

给出一个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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: