var
a,b:array[1..5000,0..5000] of longint;
d,f:array[1..100000] of longint;
bz:array[1..10000] of boolean;
i,j,k,l,x,y,z,n,m,s,t:longint;
begin
read(n,m,s,t);
fillchar(b,sizeof(b),0);
fillchar(d,sizeof(d),0);
fillchar(bz,sizeof(bz),false);
for i:=1 to m do
begin
read(x,y,z);
inc(b[x,0]);
b[x,b[x,0]]:=y;
a[x,y]:=z;
inc(b[y,0]);
b[y,b[y,0]]:=x;
a[y,x]:=z;
end;
i:=0;
j:=1;
d[1]:=s;
fillchar(f,sizeof(f),127);
f[s]:=0;
bz[s]:=true;
while i<j do
begin
inc(i);
k:=d[i];
for l:=1 to b[k,0] do
begin
if f[b[k,l]]>f[k]+a[k,b[k,l]] then
begin
f[b[k,l]]:=f[k]+a[k,b[k,l]];
if bz[b[k,l]]=false then
begin
bz[b[k,l]]:=true;
inc(j);
d[j]:=b[k,l];
end;
end;
end;
bz[k]:=false;
end;
writeln(f[t]);
end.
var
a:array[1..5000,1..5000] of longint;
b:array[1..5000,0..5000] of longint;
bz:array[1..5000] of boolean;
f:array[1..5000] of longint;
i,x,n,m,s,t,y,z,min:longint;
begin
assign(input,'dij.in'); reset(input);
assign(output,'dij.out'); rewrite(output);
read(n,m,s,t);
fillchar(b,sizeof(b),0);
for i:=1 to m do
begin
read(x,y,z);
a[x,y]:=z;
a[y,x]:=z;
inc(b[x,0]);
inc(b[y,0]);
b[x,b[x,0]]:=y;
b[y,b[y,0]]:=x;
end;
fillchar(f,sizeof(f),127);
fillchar(bz,sizeof(bz),false);
f[s]:=0;
x:=s;
repeat
bz[x]:=true;
for i:=1 to b[x,0] do
begin
if (a[x,b[x,i]]>0)and(bz[b[x,i]]=false)and(f[x]+a[x,b[x,i]]<f[i]) then
f[b[x,i]]:=a[x,b[x,i]]+f[x];
end;
min:=maxlongint;
for i:=1 to n do
begin
if (bz[i]=false)and(f[i]<min) then begin min:=f[i]; x:=i; end;
end;
until min=maxlongint;
writeln(f[t]);
close(input); close(output);
end.
一般情况下,spfa用的多一点。好打容易理解而且一般能过。
spfa题目:
IOIOI卡片占卜
NOIP2013提高组 华容道
都是我的博客