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
代码:
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include <stdio.h>
#include<vector>
#include<map>
#include<queue>
#include<iostream>
#include <algorithm>
using namespace std;
#define maxn 100086
#define inf 0x3f3f3f3f
struct edge
{
int to,cap,rev;
//终点,容量,反向边
};
vector<edge>G[maxn];
int level[maxn];
int iter[maxn];
void add(int from,int to,int cap)
{
edge a;
a.to=to;
a.cap=cap;
a.rev=G[to].size();
G[from].push_back(a);
a.to=from;
a.cap=0;
a.rev=G[from].size()-1;
G[to].push_back(a);
}
void bfs(int s)//分层
{
memset(level,-1,sizeof(level));
queue<int>que;
level[s]=0;
que.push(s);
while(!que.empty())
{
int v=que.front();
que.pop();
for(int i=0; i<G[v].size(); i++)
{
edge &e=G[v][i];
if(e.cap>0&&level[e.to]<0)
{
level[e.to]=level[v]+1;
que.push(e.to);
}
}
}
}
int dfs(int v,int t,int f)//源点 汇点 流量 找路
{
if(v==t)
{
return f;
}
for(int &i=iter[v]; i<G[v].size(); i++)
{
edge &e=G[v][i];
if(e.cap>0&&level[v]<level[e.to])
{
int d=dfs(e.to,t,min(f,e.cap));
if(d>0)
{
e.cap-=d;
G[e.to][e.rev].cap+=d;
return d;
}
}
}
return 0;
}
int main()
{
int n,m;
int t,o=0;
cin>>t;
while(t--)
{
cin>>m>>n;
{
for(int i=0; i<m; i++)
{
G[i].clear();
}
for(int i=0; i<n; i++)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
int ans=0,t=m;
for(;;)
{
bfs(1);//不断分层
if(level[t]<0)
break;
memset(iter,0,sizeof(iter));
int f;
while((f=dfs(1,t,inf))>0)
{
ans+=f;
}
}
cout<<"Case "<<++o<<": ";
cout<<ans<<endl;
}
}
}