POJ 1273 Drainage Ditches
Posted brucemengbm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 1273 Drainage Ditches相关的知识,希望对你有一定的参考价值。
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 54766 | Accepted: 20880 |
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
哈哈,第一道网络流!!!
模板一次敲对。基础理解差点儿相同了吧。
在代码中解释一下吧!
本来就仅仅有Edmonds-karp算法,如今补上Dinic算法。
AC代码例如以下:
Edmonds-karp算法例如以下:
#include<iostream> #include<cstring> #include<queue> #define inf 100000000 using namespace std; int n,m; int map[205][205],p[205];//map存网络图。p[]记录下标的流的来源。 int f[205];//用于增广路的最大增流量统计 int bfs(int s,int e) { int i,j; queue <int > q; for(i=1;i<=n;i++) {p[i]=-1;} f[1]=inf; int a,b; q.push(s); while(!q.empty()) { b=q.front(); q.pop(); if(b==e)//找到终点 break; for(i=2;i<=n;i++) { if(map[b][i]>0&&p[i]==-1) { p[i]=b; f[i]=min(f[b],map[b][i]); q.push(i); } } } if(p[e]==-1)//没有增广路了 return -1; else return f[e]; } int maxflow(int s,int e) { int i,j; int in; int ans=0; in=bfs(s,e);//用BFS找增广路 while(in!=-1) { int k=e; while(k!=s) { map[p[k]][k]-=in;//增减时满足正向和反向的转化关系 map[k][p[k]]+=in; k=p[k]; } ans+=in;//统计增流 in=bfs(s,e); } return ans; } int main() { int i,j; int a,b,c; while(cin>>m>>n) { memset(map , 0 , sizeof map ); for(i=1;i<=m;i++) { cin>>a>>b>>c; map[a][b]+=c;//可能存在同等性质的流道,累加即可了 } cout<<maxflow(1,n)<<endl; } return 0; }
Dinic算法例如以下:
#include<iostream> #include<cstring> #include<queue> #define inf 100000000 #define min(a,b) (a<b?a:b) using namespace std; int n,m; int map[205][205],cs[205]; int bfs () { int i,a,b; queue <int > q; memset(cs , -1 , sizeof cs); cs[1]=0; q.push(1); while(!q.empty()) { a=q.front (); q.pop(); for(i=1;i<=n;i++) { if(cs[i]<0&&map[a][i]>0) { cs[i]=cs[a]+1; q.push(i); } } } if(cs[n]==-1) return 0; else return 1; } int dfs(int x,int mf) { int i,j; int a; if(x==n) return mf; for(i=1;i<=n;i++) { if(cs[i]==cs[x]+1&&map[x][i]>0&&(a=dfs(i,min(mf,map[x][i])))) { map[x][i]-=a; map[i][x]+=a; return a; } } return 0; } int main() { int i,j; int a,b,c; int sum; while(cin>>m>>n) { memset(map,0,sizeof map); for(i=1;i<=m;i++) { cin>>a>>b>>c; map[a][b]+=c; } int ans=0; while(bfs())//不断构建层次图 { while(sum=dfs(1,inf))//搜索路径 ans+=sum; } cout<<ans<<endl; } return 0; }
以上是关于POJ 1273 Drainage Ditches的主要内容,如果未能解决你的问题,请参考以下文章