- 城市连接
- 2014-10-29 20:14:19 @
写了一个spfa,结果AC,写了个dijks,结果样例都不对,求大神帮我看看哪里有错。
const k=1000;
var map:array[1..k,1..k] of integer;
path:array[1..k] of integer;
s:array[1..k] of boolean;
dist:array[1..k] of longint;
n:integer;
procedure init;
var i,j:longint;
begin
readln(n);
for i:=1 to n do
begin
for j:=1 to n do
read(map[i,j]);
if map[i,j]=0 then map[i,j]:=maxint;
end;
end;
procedure print(i:integer);
var pre:integer;
begin
if i=1 then write(1)
else begin
print(path[i]);
write(' ',i);
end;
end;
procedure dijks;
var i,j,k,min,vj:longint;
begin
for i:=1 to n do s[i]:=false;
for i:=1 to n do path[i]:=1;
for i:=1 to n do dist[i]:=map[i,j];
s[1]:=true;
for k:=1 to n-2 do
begin
min:=maxint;
for j:=1 to n do
if (dist[j]<min) and not s[j] then
begin
min:=dist[j];
vj:=j;
end;
if min=maxint then exit;
s[vj]:=true;
for j:=1 to n do
if min+map[vj,j]<dist[j] then
begin
dist[j]:=min+map[vj,j];
path[j]:=vj;
end;
end;
print(j);
writeln;
writeln(dist[j]);
end;
begin
init;
dijks;
end.
2 条评论
-
第七维度丶 LV 9 @ 2014-10-30 07:54:45
Dijkstra初始化的时候 dist[i]:=map[1,i] 才对 因为你求的是顶点编号为1的点到编号为n的点的最短路 dist[i]表示的是编号为1的点到编号为i的点的最短路
-
2014-10-29 22:21:20@
program p1635;
var
a:Array[1..1000,1..1000]of INT64;
d,fa,x,c:Array[1..1000000]of INT64;
i,j,k,l,n,m,now,he,ti:longint;
begin
read(n);
for i:=1 to n do for j:=1 to n do begin
read(k);a[i,j]:=k;end;
for i:=1 to n do for j:=1 to n do
if (a[i,j]=0)and(i<>j) then a[i,j]:=1000000000;
for i:=2 to n do d[i]:=1000000000;
he:=0;ti:=1;x[1]:=1;
while he<ti do begin
inc(he);
for i:=1 to n do if (a[x[he],i]+d[x[he]]<d[i]) then
begin fa[i]:=x[he];inc(ti);x[ti]:=i;d[i]:=a[x[he],i]+d[x[he]];end;
end;
now:=n;
while fa[now]<>1 do begin inc(m);c[m]:=fa[now];now:=fa[now];end;
write(1,' ');
for i:=m downto 1 do write(c[i],' ');writeln(n);
writeln(d[n]);
end.
- 1