#include<cstdio> #include<climits> #include<cstring> #include<algorithm> const int MAXN=20010; const int MAXM=500010; using namespace std; struct edge { int v,next,val; }e[MAXM]; int p[MAXN],eid; int n,m; int h[MAXN]; int gap[MAXN]; int S,T; inline void add(int from,int to,int val) { e[eid].v=to;e[eid].val=val; e[eid].next=p[from]; p[from]=eid++; } inline int dfs(int pos,int cost) { if(pos==T) return cost; int j,minh=n-1,lv=cost,d; for(j=p[pos];j!=-1;j=e[j].next) { int v=e[j].v,val=e[j].val; if(val>0) { if(h[v]+1==h[pos]) { if(lv<e[j].val) d=lv; else d=e[j].val; d=dfs(v,d); e[j].val-=d; e[j^1].val+=d; lv-=d; if(h[S]>=n) return cost-lv; if(lv==0) break; } if (h[v]<minh) minh=h[v]; } } if (lv==cost) { --gap[h[pos]]; if(gap[h[pos]]==0) h[S]=n; h[pos]=minh+1; ++gap[h[pos]]; } return cost-lv; } int isap(int st,int ed) { S=st; T=ed; int ret=0; memset(gap,0,sizeof(gap)); memset(h,0,sizeof(h)); gap[st]=n; while(h[st]<n) ret+=dfs(st,INT_MAX); return ret; } int main() { scanf("%d%d",&m,&n); memset(p,-1,sizeof(p)); eid=0; for(int i=1;i<=m;++i) { int u,v,c; scanf("%d%d%d",&u,&v,&c); add(u,v,c); add(v,u,0); } printf("%d\n",isap(1,n)); return 0; }
原文地址:http://blog.csdn.net/wxjlzbcd/article/details/43459905