参照《挑战程序设计竞赛》
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<vector> 8 using namespace std; 9 const int MAXN=1100; 10 const int INF=0x7fffffff; 11 int n,m;//n:edges,m:points 12 struct node 13 { 14 int to,pos,cap; 15 }; 16 vector<node> E[MAXN]; 17 int vis[MAXN]; 18 19 void addedge(int u,int v,int w) 20 { 21 E[u].push_back((node){v,E[v].size(),w}); 22 E[v].push_back((node){u,E[u].size()-1,0}); 23 } 24 25 int dfs(int s,int t,int f) 26 { 27 if (s==t) return f; 28 vis[s]=1;//不要忘记这里要设置为访问过 29 for (int i=0;i<E[s].size();i++) 30 { 31 node &tmp=E[s][i]; 32 if (vis[tmp.to]==0 && tmp.cap>0) 33 { 34 int delta=dfs(tmp.to,t,min(tmp.cap,f)); 35 if (delta>0) 36 { 37 tmp.cap-=delta; 38 E[tmp.to][tmp.pos].cap+=delta; 39 return delta; 40 } 41 } 42 } 43 return 0; 44 } 45 46 int maxflow(int u,int v) 47 { 48 int flow=0; 49 for (;;) 50 { 51 memset(vis,0,sizeof(vis)); 52 int f=dfs(u,v,INF); 53 if (f==0) return flow; 54 else flow+=f; 55 } 56 } 57 58 int main() 59 { 60 while(~scanf("%d%d",&n,&m)) 61 { 62 memset(E,0,sizeof(E)); 63 for (int i=0;i<n;i++) 64 { 65 int x,y,z; 66 scanf("%d%d%d",&x,&y,&z); 67 addedge(x,y,z); 68 } 69 cout<<maxflow(1,m)<<endl; 70 } 71 return 0; 72 }