一道最大流问题,很基础,但数据有点坑,就是图有重边。
我用的是EK算法。这个算法利用了BFS去求最短的增广路,这是这个算法与其他求最大流算法的一个区别。
我的代码参考自《算法竞赛入门经典》 刘汝佳(P209)。如果觉得这本书讲得不够详细,还可以参考《ACM—ICPC程序设计系列 图论及应用》(哈尔滨工业大学出版社)P154,这里更清楚的介绍了算法的基本思路。为了方便大家了解这个算法,这里贴一个网页链接,里面讲解了EK算法:http://www.wutianqi.com/?p=3107。
代码(G++):
#include <cstdlib>
#include <iostream>
#include <queue>
#define MAX 16
#define INF 99999999
using namespace std;
int pre[MAX],val[MAX],capacity[MAX][MAX],flow[MAX][MAX];
int main(int argc, char *argv[])
{
int t,n,m,x,y,c,i,ans,u,p;
queue<int> q;
scanf("%d",&t);
p=0;
while(t--)
{
p++;
scanf("%d %d",&n,&m);
memset(capacity,0,sizeof(capacity));
for(i=0;i<m;i++)
{
scanf("%d %d %d",&x,&y,&c);
capacity[x][y]+=c; //有重边
}
memset(flow,0,sizeof(flow));
ans=0;
while(1)
{
q.push(1);
memset(val,0,sizeof(val));
val[1]=INF;
while(!q.empty())
{
u=q.front();
q.pop();
for(i=1;i<=n;i++)
{
if(!val[i]&&capacity[u][i]>flow[u][i])
{
q.push(i);
pre[i]=u;
val[i]=val[u]<?(capacity[u][i]-flow[u][i]);
}
}
}
if(0==val[n]) break;
ans+=val[n];
for(i=n;i!=1;i=pre[i])
{
flow[pre[i]][i]+=val[n];
flow[i][pre[i]]-=val[n];
}
}
printf("Case %d: %d\n",p,ans);
}
system("PAUSE");
return EXIT_SUCCESS;
}
题目( http://acm.hdu.edu.cn/showproblem.php?pid=3549):
Flow Problem
Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Problem Description
Network flow is a well-known difficult problem for ACMers. Given a graph, your task is to find out the maximum flow for the weighted directed graph.
Input
The first line of input contains an integer T, denoting the number of test cases.
For each test case, the first line contains two integers N and M, denoting the number of vertexes and edges in the graph. (2 <= N <= 15, 0 <= M <= 1000)
Next M lines, each line contains three integers X, Y and C, there is an edge from X to Y and the capacity of it is C. (1 <= X, Y <= N, 1 <= C <= 1000)
For each test case, the first line contains two integers N and M, denoting the number of vertexes and edges in the graph. (2 <= N <= 15, 0 <= M <= 1000)
Next M lines, each line contains three integers X, Y and C, there is an edge from X to Y and the capacity of it is C. (1 <= X, Y <= N, 1 <= C <= 1000)
Output
For each test cases, you should output the maximum flow from source 1 to sink N.
Sample Input
2 3 2 1 2 1 2 3 1 3 3 1 2 1 2 3 1 1 3 1
Sample Output
Case 1: 1 Case 2: 2