tyvj P1238 - 路径
P1238 - 路径From lwz_th Normal (OI) 总时限:10s 内存限制:128MB |
|||||||
|---|---|---|---|---|---|---|---|
|
|||||||
Delphi语言: 高亮代码由发芽网提供
program tyvj1238;
type node=record
a,b:int64;
end;
var a:array[0..99,0..99] of longint;
d:array[0..99] of node;
q:array[1..1000000] of integer;
b:array[0..99,0..100] of integer;
mark:array[0..99] of boolean;
n,m,u,v,w,head,tail,k:int64;i:longint;
procedure push(k:longint);
begin
inc(head);q[head]:=k;
mark[k]:=true;
end;
function pop:longint;
begin
pop:=q[tail];inc(tail);
end;
begin
readln(n,m);
fillchar(mark,sizeof(mark),false);
for i:=1 to m do begin
readln(u,v,w);
inc(b[u,0]);
b[u,b[u,0]]:=v;
a[u,v]:=w;
end;
for i:=1 to n-1 do begin
d[i].a:=maxlongint;
d[i].b:=maxlongint;
end;
d[0].a:=0;d[0].b:=0;
head:=0;tail:=1;
push(0);
while head>=tail do begin
k:=pop;
for i:=1 to b[k,0] do begin
if d[b[k,i]].a>d[k].a+1 then begin
d[b[k,i]].b:=d[k].b+a[k,b[k,i]];
d[b[k,i]].a:=d[k].a+1;
if not mark[b[k,i]] then push(b[k,i]);
end
else if (d[b[k,i]].a=d[k].a+1)and(d[b[k,i]].b>(d[k].b+a[k,b[k,i]])) then begin
d[b[k,i]].b:=d[k].b+a[k,b[k,i]];
if not mark[b[k,i]] then push(b[k,i]);
end;
end;
mark[k]:=false;
end;
writeln(d[1].b);
end.
图1 图2
一条路径连接了一个点Vi和另一个点Vj,其方向与经过的一系列边的方向一致。路径的长度是途经边的条数,路径的费用是边价值的总和。对于一个给定的图,你的任务是在所有最短路径中,找出需要最少费用的连接V0和V1的路径。一个需要最少费用的最短路径称之为廉价最短路径。让我们重新考虑图1,从0到1的最短路径是只含一条边的路径0→1,费用是10。当然,还有更便宜的路:0→2→1和 0→3→1,但是它们比第一条路径长(有2条边)。所以,0→1是廉价最短路径。
看一下另一个例子,图2,它有2条最短路径,其长度是2,路径0→3→1(费用=4)比路径0→2→1(费用=5)花费少。还用另一条路径0→2→3→1(费用=3),虽然便宜但是很长。所以,廉价最短路径是0→3→1。
浙公网安备 33010602011771号