网络流dinic模板:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cstdlib> #include <queue> #include<math.h> #define inf 0x3f3f3f3f #define ls l,mid,rt<<1 #define rs mid+1,r,rt<<1|1 #define maxn 10000000 using namespace std; struct node { int to,w,next; } q[300000]; int head[300000],l[300000],cnt,s,e; void bu(int a,int b,int c) { q[cnt].to=b; q[cnt].w=c; q[cnt].next=head[a]; head[a]=cnt++; q[cnt].to=a; q[cnt].next=head[b]; q[cnt].w=0; head[b]=cnt++; } int bfs() { queue<int >Q; while(!Q.empty()) Q.pop(); memset(l,-1,sizeof(l)); l[s]=0; Q.push(s); while(!Q.empty()) { int v=Q.front(); Q.pop(); for(int i=head[v]; ~i; i=q[i].next) { if(q[i].w>0&&l[q[i].to ]==-1) { l[q[i].to ]=l[v]+1; Q.push(q[i].to); } } } return l[e]!=-1; } int dfs(int x,int f) { if(x==e) { return f; } int tmp=0,a; for(int i=head[x]; ~i; i=q[i].next) { if(q[i].w>0&&(l[q[i].to ]==l[x]+1 )) { if(a=dfs(q[i].to,min(q[i].w,f-tmp))) { q[i].w-=a; q[i^1].w+=a; tmp+=a; } } } if(tmp==0) l[x]=-1; return tmp; } int main() { int n,m,i,j,k,cla,A=1; while(~scanf("%d%d",&m,&n)) { int a,b,c; cnt=0; s=1,e=n; memset(head,-1,sizeof(head)); for(i=0; i<m; i++) { scanf("%d%d%d",&a,&b,&c); bu(a,b,c); } int ans=0; while(bfs()) { ans+=dfs(1,inf); } printf("%d\n",ans); } return 0; }