POJ 1273 Drainage Ditches | 最大流模板
#include<cstdio> #include<algorithm> #include<cstring> #include<queue> #define N 250 #define M 250 #define INF 100000000 using namespace std; int head[N],cur[N],lev[N],ecnt=1,S,T,n,m; queue <int> q; struct adj { int nxt,v,w; }e[2*M]; void add(int u,int v,int w) { e[++ecnt].v=v,e[ecnt].w=w,e[ecnt].nxt=head[u],head[u]=ecnt; e[++ecnt].v=u,e[ecnt].w=0,e[ecnt].nxt=head[v],head[v]=ecnt; } inline int bfs() { int u,v; for (int i=S;i<=T;i++) lev[i]=-1,cur[i]=head[i]; q.push(S),lev[S]=0; while (!q.empty()) { u=q.front(); for (int i=head[u];i;i=e[i].nxt) { if (e[i].w>0 && lev[v=e[i].v]==-1) lev[v]=lev[u]+1,q.push(v); } q.pop(); } return lev[T]!=-1; } inline int Dinic(const int &u,const int &flow) { if (u==T) return flow; int res=0,v,delta; for (int &i=cur[u];i;i=e[i].nxt) { if (e[i].w>0 && lev[u]<lev[v=e[i].v]) { delta=Dinic(v,min(e[i].w,flow-res)); if (delta) { e[i].w-=delta;e[i^1].w+=delta; res+=delta;if (res==flow) break; } } } if (res!=flow) lev[u]=-1; return res; } inline int Maxflow() { int ans=0; while (bfs()) ans+=Dinic(S,INF); return ans; } inline void init() { memset(head,0,sizeof(head)); ecnt=1; } int main() { while (scanf("%d%d",&n,&m)!=EOF) { init(); for (int i=1,x,y,z;i<=n;i++) { scanf("%d%d%d",&x,&y,&z); add(x,y,z); } S=1,T=m; printf("%d\n",Maxflow()); } return 0; }