Dinic模板 poj 1273 发表于 2016-12-09 | 分类于 ~❤程序❤~ , 网络流 , 最大流 一道简单而直接的网络流模板 以前一直以为Dinic很难,不敢写,现在看起来并不是特别的长和难写啊。其实Dinic还是非常的好写,网络流还是难在建图啊,裸的Dinic就不讲思路了。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>#include<vector>#include<queue>using namespace std;int n,m;struct table{ int to,id;};vector<table> ve[444];int tot=0;int f[444],deep[444];int min(int a,int b){ if(a<=b) return a; else return b;}bool bfs(){ memset(deep,-1,sizeof(deep)); queue<int> q; deep[1]=0; q.push(1); while(!q.empty()) { int x=q.front();q.pop(); for(int i=0;i<ve[x].size();i++) { table y=ve[x][i]; if(deep[y.to]==-1&&f[y.id]>0) { deep[y.to]=deep[x]+1; q.push(y.to); } } } return deep[n]!=-1;}int zeng(int a,int b){ if(a==n) return b; int r=0,t; for(int i=0;i<ve[a].size()&&b>r;i++) { table y=ve[a][i]; if(deep[y.to]==deep[a]+1&&f[y.id]>0) { t=zeng(y.to,min(b-r,f[y.id])); r+=t,f[y.id]-=t,f[y.id^1]+=t; } } if(!r) deep[a]=-1; return r;}int dinic(){ int ans=0,now; while(bfs()) { while(now=zeng(1,247483647)) ans+=now; } return ans;}int main(){ while(scanf("%d%d",&m,&n)!=EOF) { for(int i=1;i<=m;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); ve[x].push_back((table){y,tot}),f[tot++]=z; ve[y].push_back((table){x,tot}),f[tot++]=0; } printf("%d\n",dinic()); for(int i=1;i<=n;i++) ve[i].clear(); tot=0; } return 0;}