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)
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
刚学最大流,用ek算法写一波以后再学别的再补充,原理懂了应该能理解代码。
http://blog.sina.com.cn/s/blog_6cf509db0100uy5n.html
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<string.h>
#define maxn 20
#define inf 0x3f3f3f3f
using namespace std;
int n,m,cas=0,star,last;
queue<int>que;
int gra[maxn][maxn],path[maxn],flow[maxn];
int bfs()
{
int t;
while(!que.empty())que.pop();
memset(path,-1,sizeof(path));
path[star]=0,flow[star]=inf;
que.push(star);
while(!que.empty())
{
t=que.front();
que.pop();
if(t==last) break;
for(int i=1;i<=n;i++)
{
if(i!=star && path[i]==-1 && gra[t][i])
{
flow[i]=flow[t]<gra[t][i]?flow[t]:gra[t][i];
que.push(i);
path[i]=t;
}
}
}
if(path[last]==-1)return -1;
return flow[n];
}
int Edmods_Karp()
{
int max_flow=0,step,now,pre;
while((step=bfs())!=-1)
{
max_flow+=step;
now=last;
while(now!=star)
{
pre=path[now];
gra[pre][now]-=step;
gra[now][pre]+=step;
now=pre;
}
}
return max_flow;
}
int main()
{
int t,x,y,z;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(gra,0,sizeof(gra));
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
gra[x][y]+=z;
}
star=1,last=n;
printf("Case %d: %d\n",++cas,Edmods_Karp());
}
return 0;
}