Cod sursa(job #1173156)

Utilizator azkabancont-vechi azkaban Data 18 aprilie 2014 18:44:11
Problema Algoritmul Bellman-Ford Scor 5
Compilator fpc Status done
Runda Arhiva educationala Marime 1.83 kb
Program dijkstra;
type lista = ^celula;
     celula = record
                    nod : longint;
                    cost : longint;
                    pred : lista;
               end;

const INF=200000000;
var Lda : array [1..300000] of lista;
    r  :lista;
    Coada,D,viz: array [1..300005] of longint;
    n,i,a,b,c,v,aux,p,beg,sf,k: longint;
    b1,b2 : array[0..1 shl 17] of char;

begin
   assign(input,'bellmanford.in'); settextbuf(input,b1); reset(input);
   assign(output,'bellmanford.out'); settextbuf(output,b2);rewrite(output);
   readln(n,p); aux:=n; k:=0;
   for i:=1 to n do viz[i]:=0;
   for i:=1 to p do begin
                        readln(a,b,c);
                        new(r);
                        r^.nod:=b;
                        r^.cost:=c;
                        r^.pred:=lda[a];
                        lda[a]:=r;
                    end;
   for i:=2 to n do D[i]:=INF;
   coada[1]:=1; beg:=1; sf:=1;
   viz[1]:=1;
   while beg<=sf do begin
                         v:=coada[beg];
                         r:=lda[coada[beg]];
                         while r<>nil do begin
                            if D[v]+r^.cost<D[r^.nod] then D[r^.nod]:=D[v]+r^.cost;
                            if viz[r^.nod]=0 then begin
                                                    viz[r^.nod]:=1;
                                                    sf:=sf+1;
                                                    coada[sf]:=r^.nod;
                                                    end;
                                              r:=r^.pred;
                                           end;

                          beg:=beg+1;
                     end;
   for i:=2 to aux do
                   if D[i]=INF then write(0,' ')
                               else write(D[i],' ');

   close(output);
end.