从ford_fuckerman算法进步到dinic算法

dinic算法思路:1.宽搜,将图分层,没有到汇点的路则停止算法,此时即为最大流

                            2.深搜,按层找增广路,直至没路

                            3.重复1.


参考程序:

type
  edge=record
        tt,v,next:longint;
       end;
const
  INF=maxlongint shr 2;
var
  cnt,x,y,z,start,stop,n,m,maxflow,i:longint;
  h,a,q:array[0..100000]of longint;
  e:array[0..200000]of edge;
procedure insert(u,v,w:longint);
begin
  cnt:=cnt+1;
  e[cnt].tt:=v;
  e[cnt].v:=w;
  e[cnt].next:=a[u];
  a[u]:=cnt;
end;
function min(a,b:longint):longint;
begin
  if a<b then exit(a);
  exit(b);
end; 
function bfs:boolean;
var
  head,i,now,tail:longint;
begin
  fillchar(h,sizeof(h),$ff);
  head:=0;tail:=1;
  q[1]:=start;h[start]:=0;
  while head<tail do
   begin
     head:=head+1;
     now:=q[head];
     i:=a[now];
     while i>0 do
      begin
        if (e[i].v>0)and(h[e[i].tt]=-1) then
         begin
           tail:=tail+1;
           q[tail]:=e[i].tt;
           h[e[i].tt]:=h[now]+1;
         end;
        i:=e[i].next;
      end;
   end;
  if h[stop]=-1 then exit(false);
  exit(true);
end;
function dfs(x,f:longint):longint;
var
  w,used,i:longint;
begin
  if x=stop then exit(f);
  used:=0;i:=a[x];
  while i>0 do
   begin
     if (e[i].v>0)and(h[e[i].tt]=h[x]+1) then
      begin
        w:=f-used;
        w:=dfs(e[i].tt,min(e[i].v,w));
        e[i].v:=e[i].v-w;
        e[i xor 1].v:=e[i xor 1].v+w;
        used:=used+w;
        if used=f then exit(f);
      end;
     i:=e[i].next;
   end;
  if used=0 then h[x]:=-1;
  exit(used);
end;
begin
  readln(n,m);
  for i:=1 to m do
   begin
     readln(x,y,z);
     insert(x,y,z);
     insert(y,x,0);
   end;
  readln(start,stop);
  while bfs do maxflow:=maxflow+dfs(start,INF);
end.

你可能感兴趣的:(从ford_fuckerman算法进步到dinic算法)