1 procedure dinic;
2 begin
3 while bfs do inc(ans,dfs(s,maxlongint));
4 end;
5
6 function bfs:boolean;
7 var h,tail,i,j:longint;
8 begin
9 fillchar(dis,sizeof(dis),$3f);
10 h:=0;tail:=1;l[1]:=s;dis[s]:=0;
11 while h<>tail do
12 begin
13 inc(h);i:=l[h];j:=head[i];
14 while j>0 do
15 begin
16 if(dis[i]+1<dis[q[j]])and(flow[j]>0) then
17 begin
18 inc(tail);l[tail]:=q[j];
19 dis[q[j]]:=dis[i]+1;
20 end;
21 j:=next[j];
22 end;
23 end;
24 if dis[t]=$3f3f3f3f then exit(false) else exit(true);
25 end;
26
27 function dfs(i,ll:longint):longint;
28 var j,tmp,x:longint;
29 begin
30 if i=t then exit(ll);
31 j:=head[i];x:=0;
32 while j>0 do
33 begin
34 if(flow[j]>0)and(dis[q[j]]=dis[i]+1) then
35 begin
36 tmp:=dfs(q[j],min(ll-x,flow[j]));
37 dec(flow[j],tmp);
38 inc(flow[j xor 1],tmp);
39 inc(x,tmp);
40 if x=ll then exit(ll);
41 end;
42 j:=next[j];
43 end;
44 if x=0 then dis[i]:=-1;
45 exit(x);
46 end;