NUM.ONE——dijkstra单源最短路
var a:array[1..100,1..100]of longint;
i,j,k,l,m,n,max,maxp:longint;
dist:array[1..100]of longint;
v:array[1..1000]of boolean;
begin
readln(n);
for i:=1 to n do
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]=0 then
a[i,j]:=maxlongint;
end;
for i:=1 to n do
dist[i]:=a[1,i];
fillchar(v,sizeof(v),true);
v[1]:=false;
max:=maxlongint;
for k:=1 to n-1 do
begin
for i:=2 to n do
if (a[1,i]and(v[i]) then
begin
max:=a[1,i];
maxp:=i;
end;
v[maxp]:=false;
for j:=1 to n do
if v[j] then
if a[maxp,j]then
if dist[j]>dist[maxp]+a[maxp,j] then
dist[j]:=dist[maxp]+a[maxp,j];
end;
for i:=1 to n do
write(dist[i],' ');
end.
NUM.TWO——bellman ford算法
var a:array[1..1000,1..100]of longint;
d:array[1..1000]of longint;
i,j,k,l,m,n:longint;
change:boolean;
begin
readln(n);
for i:=1 to n do
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]=0 then
a[i,j]:=maxlongint;
end;
for i:=1 to n do
d[i]:=a[1,i];
for l:=1 to n-1 do
for i:=1 to n do
for j:=1 to n do
if a[i,j]<>maxlongint then
if d[j]<>maxlongint then
if d[i]>d[j]+a[i,j] then
d[i]:=d[j]+a[i,j];
change:=true;
for i:=1 to n do
for j:=1 to n do
if d[i]>d[j]+a[i,j] then
begin
change:=false;
writeln('not possible');
halt;
end;
for i:=1 to n do
write(d[i],' ');
end.
NUM.THREE——SPFA
var a,b:array[1..1000,0..100]of longint;
d,dist:array[1..1000]of longint;
v:array[1..1000]of boolean;
c:array[1..100,1..100]of boolean;
i,j,k,l,m,n:longint;
head,tail:longint;
procedure spfa;
var i,j,k,l,m,now:longint;
begin
fillchar(d,sizeof(d),0);
fillchar(v,sizeof(v),false);
for i:=1 to n do
dist[i]:=maxlongint;
dist[1]:=0;
v[1]:=true;
head:=1;
tail:=1;
d[1]:=1;
while head<=tail do
begin
now:=d[head];
for i:=1 to b[now,0]do
if (dist[now]<>maxlongint) and (a[now,b[now,i]]<>maxlongint) then
if dist[b[now,i]]>dist[now]+a[now,b[now,i]] then
begin
dist[b[now,i]]:=dist[now]+a[now,b[now,i]];
if not v[b[now,i]] then
begin
inc(tail);
d[tail]:=b[now,i];
v[b[now,i]]:=true;
end;
end;
v[now]:=false;
inc(head);
end;
end;
begin
readln(n);
fillchar(b,sizeof(b),0);
fillchar(c,sizeof(c),true);
for i:=1 to n do
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]=0 then
a[i,j]:=maxlongint;
if a[i,j]<>maxlongint then
if c[i,j] then
begin
c[j,i]:=false;
c[i,j]:=false;
inc(b[i,0]);
b[i,b[i,0]]:=j;
inc(b[j,0]);
b[j,b[j,0]]:=i;
end;
end;
spfa;
for i:=1 to n do
write(dist[i],' ');
end.