dinic版本
感觉dinic算法好帅,比Edmonds-Karp算法不知高到哪里去了
Description
Farmer John knows not only how many gallons of water each ditch can transport per minute but also the exact layout of the ditches, which feed out of the pond and into each other and stream in a potentially complex network.
Given all this information, determine the maximum rate at which water can be transported out of the pond and into the stream. For any given ditch, water flows in only one direction, but there might be a way that water can flow in a circle.
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
1 /*Dinic*/ 2 #include<iostream> 3 #include<cstdio> 4 #include<algorithm> 5 #include<cstring> 6 #include<cmath> 7 #include<queue> 8 using namespace std; 9 const int inf=0x7fffffff; 10 int n,m;//路径数 结点数 11 int fl[200][200],dis[200]; 12 int bfs(){ 13 // memset(dis,-1,sizeof(dis)); 14 for(int i=1;i<=m+5;i++)dis[i]=-1; 15 dis[1]=0;//原点层数为0 16 queue<int> q; 17 q.push(1); 18 while(!q.empty()){ 19 int k=q.front();q.pop(); 20 for(int i=1;i<=m;i++){ 21 if(fl[k][i]>0 &&dis[i]<0){ 22 dis[i]=dis[k]+1; 23 q.push(i); 24 } 25 } 26 } 27 // return (dis[m]>0); 28 if(dis[m]>0)return 1; 29 else return 0; 30 } 31 int dfs(int q,int mx){ 32 if(q==m)return mx; 33 int i,a; 34 for(i=1;i<=m;i++){ 35 if(fl[q][i]>0 && dis[i]==dis[q]+1 && (a=dfs(i,min(fl[q][i],mx))) ){ 36 fl[i][q]+=a; 37 fl[q][i]-=a; 38 return a; 39 } 40 } 41 return 0; 42 } 43 int main(){ 44 45 int i,j,u,v,d; 46 while(scanf("%d%d",&n,&m)!=EOF){ 47 memset(fl,0,sizeof(fl)); 48 49 for(i=1;i<=n;i++){ 50 scanf("%d%d%d",&u,&v,&d); 51 fl[u][v]+=d; 52 } 53 int ans=0; 54 int res; 55 while(bfs()){ 56 while(res=dfs(1,inf))ans+=res; 57 } 58 printf("%d\n",ans); 59 } 60 return 0; 61 }