Cod sursa(job #702791)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 2 martie 2012 09:20:48
Problema Algoritmul Bellman-Ford Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.23 kb
program bellman_ford;
type natural=record
 nod,cost:longint;
end;
var f,g:text;
    n,m,i,x,y,z,ps,pi,nr,wnod,wcost:longint;
    a:array of array of natural;
    bufin,bufout:array[1..65000] of char;
    viz:array[1..1000000] of longint;
    cd:array[1..1000000] of longint;
    d:array[1..1000000] of longint;

begin
 assign (f,'bellmanford.in'); reset (F);
 assign (g,'bellmanford.out'); rewrite (g);
 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
  ps:=ps+1;
  nr:=cd[ps];
  viz[nr]:=viz[nr]+1;
  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
    pi:=pi+1;
    cd[pi]:=wnod;
    d[wnod]:=d[nr]+wcost;
    viz[wnod]:=viz[wnod]+1;
    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.