网络最大流dinic模板
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 510 #define For(i,a,b) for(int i=a;i<=b;i++) #define p(a) putchar(a) #define g() getchar() using namespace std; int n,m,x,y,v,maxflow,tot; int head[N],deep[N],cur[N]; struct node{ int n; int v; int next; }e[N]; queue<int>q; void in(int &x){ int y=1; char c=g();x=0; while(c<'0'||c>'9'){ if(c=='-')y=-1; c=g(); } while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=g(); } x*=y; } void o(int x){ if(x<0){ p('-'); x=-x; } if(x>9)o(x/10); p(x%10+'0'); } void push(int x,int y,int v){ e[tot].n=y; e[tot].v=v; e[tot].next=head[x]; head[x]=tot++; } bool bfs(int s,int t){ memset(deep,-1,sizeof(deep)); For(i,1,n) cur[i]=head[i]; deep[s]=0; q.push(s); while(!q.empty()){ int now=q.front(); q.pop(); for(int i=head[now];i!=-1;i=e[i].next) if(deep[e[i].n]==-1 && e[i].v>0){ deep[e[i].n]=deep[now]+1; q.push(e[i].n); } } return deep[t]!=-1; } int dfs(int now,int t,int lim){ if(now==t||lim==0) return lim; int flow=0,f; for(int i=cur[now];i!=-1;i=e[i].next){ cur[now]=i; if(deep[e[i].n]==deep[now]+1 && (f=dfs(e[i].n,t, min(lim,e[i].v) ))){ flow+=f; lim-=f; e[i].v-=f; e[i^1].v+=f; if(!lim) break; } } return flow; } void dinic(int s,int t){ while(bfs(s,t)){ maxflow+=dfs(s,t,inf); } } int main(){ in(m);in(n); memset(head,-1,sizeof(head)); For(i,1,m){ in(x);in(y);in(v); push(x,y,v); push(y,x,0); } dinic(1,n); o(maxflow); return 0; }