Cod sursa(job #717350)

Utilizator MihaiBunBunget Mihai MihaiBun Data 19 martie 2012 21:02:05
Problema Flux maxim Scor 40
Compilator fpc Status done
Runda Arhiva educationala Marime 2.51 kb
program kk;
type ref=^inr;
     inr=record
            nr:longint;
            adr:ref
         end;
var f:text;
    i,n,m,s,x,y,min,z:longint;
    pc,uc,q,w:ref;
    viz:array[1..1000] of longint;
    flux,a:array[1..1000,1..1000] of longint;
    max:int64;
    gasit:boolean;

procedure drum;
begin
  for i:=1 to n do viz[i]:=0;
  new(pc);
  pc^.nr:=1;
  pc^.adr:=nil;
  uc:=pc;
  viz[1]:=1;
  gasit:=false;
  while (pc<>nil)and(not gasit) do
    begin
      x:=pc^.nr;
      i:=0;
      repeat
        i:=i+1;
        if not gasit then
        if a[x,i]>0 then
          if viz[i]=0 then
            if flux[x,i]<a[x,i] then begin
                                       if i=n then gasit:=true;
                                       viz[i]:=x;
                                       new(q);
                                       q^.nr:=i;
                                       q^.adr:=nil;
                                       uc^.adr:=q;
                                       uc:=q;
                                     end;
         if not gasit then
         if a[i,x]>0 then
          if viz[i]=0 then
            if flux[i,x]>0 then begin
                                       if i=n then gasit:=true;
                                       viz[i]:=-x;
                                       new(q);
                                       q^.nr:=i;
                                       q^.adr:=nil;
                                       uc^.adr:=q;
                                       uc:=q;
                                     end;
       until (i=n)or gasit;

      q:=pc;
      pc:=pc^.adr;
      dispose(q);
    end;
  if gasit then
    begin
     min:=2000000;
     y:=n;
     repeat
       x:=viz[y];
       if x>0 then begin
                     if a[x,y]-flux[x,y]<min then min:=a[x,y]-flux[x,y];
                   end
              else if flux[-x,y]<min then min:=flux[-x,y];
       y:=abs(x);
     until abs(x)=1;
     y:=n;
     repeat
       x:=viz[y];
       if x>0 then flux[x,y]:=flux[x,y]+min
              else flux[-x,y]:=flux[-x,y]-min;
       y:=abs(x);
     until abs(x)=1;
    end;
end;

begin
  assign(f,'maxflow.in');
  reset(f);
  readln(f,n,m);
  for i:=1 to m do
    begin
      readln(f,x,y,z);
      a[x,y]:=z;
    end;
  repeat
  drum;
  until not gasit;

  close(f);
  assign(f,'maxflow.out');
  rewrite(f);
  max:=0;
  for i:=2 to n do
    if a[1,i]>0 then max:=max+flux[1,i];
  write(f,max);
  close(f);
end.