Pagini recente » Cod sursa (job #1636617) | Cod sursa (job #2415129) | Cod sursa (job #2441719) | Cod sursa (job #1353504) | Cod sursa (job #745366)
Cod sursa(job #745366)
program belman_ford;
type natural=record
nod,cost:longint;
end;
var f,g:text;
n:longint;
cd:array[1..50000] of longint;
a:array of array of natural;
x,y,z,m,wnod,wcost,nr,i,ps,pi:longint;
d:array [1..50000] of longint;
bufin,bufout:array [1..65000] of byte;
viz:array[1..50000] of longint;
begin
assign (f,'bellmanford.in'); reset (f);
assign (g,'bellmanford.out'); rewrite (g);
settextbuf (f,bufin);
settextbuf (g,bufout);
readln (f,n,m);
setlength (a,n+1,1);
for i:=1 to m do
begin
readln (f,x,y,z);
setlength (a[x],length (a[x])+1);
a[x,0].nod:=a[x,0].nod+1;
a[x,a[x,0].nod].nod:=y;
a[x,a[x,0].nod].cost:=z;
end;
for i:=2 to n do
d[i]:=maxlongint;
ps:=0; pi:=1; cd[1]:=1;
while ps<pi do
begin
inc(ps);
nr:=cd[ps];
inc(viz[nr]);
for i:=1 to a[nr,0].nod do
begin
wnod:=a[nr,i].nod;
wcost:=a[nr,i].cost;
if d[wnod]>d[nr]+wcost then
begin
inc(pi);
d[wnod]:=d[nr]+wcost;
cd[pi]:=wnod;
inc(viz[wnod]);
if viz[wnod]>n then
begin
write (g,'Ciclu negativ!');
close (F); close (g);
exit;
end;
end;
end;
end;
for i:=2 to n do
begin
if d[i]=maxlongint then
d[i]:=0;
write (g,d[i],' ');
end;
close (f); close (g);
end.