Cod sursa(job #398)

Utilizator wefgefAndrei Grigorean wefgef Data 11 decembrie 2006 10:17:45
Problema PScNv Scor 80
Compilator fpc Status done
Runda Arhiva de probleme Marime 2.48 kb
program pscnv;

const filein = 'pscnv.in';
      fileout = 'pscnv.out';
      Nmax = 250000;

type pnod = ^nod;
     nod = record
       val, c : longint;
       next : pnod;
     end;

var N, M, X, Y, a, b, c, min, i, j, lung, elem : longint;
    vec : array[1..Nmax] of pnod;
    viz : array[1..Nmax] of boolean;
    heap, loc, el : array[1..Nmax] of longint;
    p : pnod;
    str : string;

procedure reconst(k : longint); inline;
var poz, aux : longint;
begin
if k = 1 then exit;
poz := k shr 1;
if heap[poz] > heap[k] then
  begin
    aux:= heap[poz];
    heap[poz] := heap[k];
    heap[k] := aux;

    aux := el[poz];
    el[poz] := el[k];
    el[k] := aux;

    loc[el[poz]] := poz;
    loc[el[k]] := k;

    reconst(poz);
  end;
end;

procedure insert(val, cost : longint);  inline;
begin
inc(lung);
heap[lung] := cost;
loc[val] := lung;
el[lung] := val;
reconst(lung);
end;

procedure reconst2(k : longint); inline;
var max, aux : longint;
begin
max := k;
if k shl 1 <= lung then
if heap[k shl 1] < heap[max] then max := k shl 1;

if (k shl 1) +1 <= lung then
if heap[(k shl 1) +1] < heap[max] then max := ( k shl 1) + 1;

if max > k then
  begin
    aux:= heap[max];
    heap[max] := heap[k];
    heap[k] := aux;

    aux := el[max];
    el[max] := el[k];
    el[k] := aux;

    loc[el[max]] := max;
    loc[el[k]] := k;

    reconst2(max);
  end;
end;

procedure scoate; inline;
begin
heap[1] := heap[lung];
el[1] := el[lung];
loc[el[1]] := 1;
dec(lung);
reconst2(1);
end;

begin
assign(input, filein); reset(input);
read(N, M, X, Y);

for i := 1 to M do
  begin
    read(a, b, c);
    new(p); p^.next := vec[a];
    p^.val := b; p^.c := c;
    vec[a] := p;
  end;
close(input);

assign(output, fileout); rewrite(output);
viz[X] := true;
p := vec[X];
while p <> nil do
  begin
    insert(p^.val, p^.c);
    p := p^.next;
  end;

while not viz[Y] do
  begin
    if heap[1] > min then min := heap[1];
    elem := el[1];
    viz[elem] := true;
    scoate;
    p := vec[elem];
    while p <> nil do
      begin
        if not viz[p^.val] then
          begin
            if loc[p^.val]=0 then
              insert(p^.val, p^.c)
            else
            if p^.c < heap[loc[p^.val]] then
              begin
                heap[loc[p^.val]] := p^.c;
                reconst(loc[p^.val]);
              end;
          end;
        p := p^.next;
      end;
  end;

writeln(min);
close(output);
end.