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
SOURCE:点击打开链接
题意:
赤裸裸的网络流题目。给定点数,边数,每条边的容量,以及源点,汇点,求最大流。
解析:
通过Ford-Fulkerson算法或者是Dinic算法,通过dfs搜索最小流进行增广路。
Ford-Fulkerson算法:
#include <iostream>
#include <cstring>
#include <algorithm>
#define MAX 205
#define INF 0x7fffffff
using namespace std;
int n,m;
int c[MAX][MAX];
bool pass[MAX];
int dfs(int s,int t,int low);//s为源点,t为汇点,low为当前流
int dfs_max_flow(int s,int t);
int main(void)
{
int a,b,d;
while (cin>>n>>m)
{
memset(c,0,sizeof(c));
for (int i=1; i<=n; ++i)
{
cin>>a>>b>>d;
c[a][b]+=d;
}
cout<<dfs_max_flow(1,m)<<endl;
}
return 0;
}
int dfs(int s,int t,int low)
{
if (s==t)
return low;
pass[s]=1;
for (int i=1; i<=m; ++i)
{
if (!pass[i]&&c[s][i])
{
int flow=dfs(i,t,min(low,c[s][i]));
if(flow>0) //增广该路径
{
c[s][i]-=flow;
c[i][s]+=flow;
return flow;
}
}
}
return 0;
}
int dfs_max_flow(int s,int t)
{
memset(pass,0,sizeof(pass));
int maxflow=0,flow;
while (flow=dfs(s,t,INF)) //不断地增广路径进行搜索,直到无法继续增加才结束
{
memset(pass,0,sizeof(pass));
maxflow+=flow;
}
return maxflow;
}
Dinic算法:
#include<iostream>
#include<cstring>
#include<queue>
#define maxn 205
#define INF 0x7fffffff
using namespace std;
int n, m;
int c[maxn][maxn];
int dis[maxn];//dis[i]表示到原点s的层数
bool bfs();
int dfs(const int x,const int low);
int main(void)
{
int s,t,d;
while(cin>>n>>m)
{
memset(c,0,sizeof(c));
for(int i = 0 ; i < m; i++)
{
cin>>s>>t>>d;
c[s][t] += d;
}
int ans = 0;
int res;
while(bfs())
while(res = dfs(1,INF))
ans+= res;
cout<<ans<<endl;
}
return 0;
}
bool bfs()// 重新建图按层数建图
{
memset(dis,-1,sizeof(dis));
int k;
dis[1] = 0;
queue<int> que;
que.push(1);
while(que.size())
{
k = que.front();
que.pop() ;
for( int i = 1; i<= m; i++)
if(c[k][i] > 0 && dis[i] < 0 )// 如果 可以 可以到达 但 还没有 访问
{
dis[i] = dis[k]+ 1;
que.push(i);
}
}
if(dis[n] > 0)
return true;
else
return false;
}
int dfs(const int x,const int low)// 查找路径上的最小的流量
{
int flow;
if(x == n)
return low;
for(int i = 1; i<= n; i++)
if(c[x][i] > 0 && dis[i] == dis[x] + 1)
{
flow=dfs(i,min(low,c[x][i]));
if(flow>0)
{
c[x][i] -= flow;
c[i][x] += flow;
return flow;
}
}
return 0;
}
10万+




被折叠的 条评论
为什么被折叠?



