1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
Uses math;
var value,reach,cnt,next,gap,dis:array[0..2100000] of longint; n,m,source,sink,tot,x,y,sum,i:longint; maxflow:int64;
procedure add(x,y,sum:longint); begin inc(tot); reach[tot]:=y; inc(value[tot],sum); next[tot]:=cnt[x]; cnt[x]:=tot; end;
function Dfs(now,flow:longint):longint; var i,k,mindis,ret:longint; begin mindis:=n-1; ret:=flow; if now=sink then exit(flow);
i:=cnt[now]; repeat if value[i]>0 then begin if dis[now]=dis[reach[i]]+1 then begin k:=Dfs(reach[i],min(ret,value[i])); dec(value[i],k); inc(value[i xor 1],k); dec(ret,k); if dis[source]>=n then exit(flow-ret); if ret=0 then break; end; mindis:=min(mindis,dis[reach[i]]); end; i:=next[i]; until i=-1;
if ret=flow then begin dec(gap[dis[now]]); if gap[dis[now]]=0 then dis[source]:=n; dis[now]:=mindis+1; inc(gap[dis[now]]); end; exit(flow-ret); end;
begin filldword(cnt,sizeof(cnt) div 4,maxlongint*2+1); tot:=1; read(n,m,source,sink); for i:=1 to m do begin read(x,y,sum); add(x,y,sum); add(y,x,0); end;
gap[source]:=n; while dis[source]<n do inc(maxflow,Dfs(source,maxlongint)); writeln(maxflow); end.
|