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<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#define CLR(a,b) memset((a),(b),sizeof(a))
#define inf 0x3f3f3f3f
#define mod 100009
#define LL long long
#define M 3000+100
#define ll o<<1
#define rr o<<1|1
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
using namespace std;
struct Edge {
int from,to,cap,flow,next;
}edge[M]; // 边 cap 最大流量,flow 目前的流量,
int vis[M];
int head[M];
int dis[M]; // 记录 层次图
int cur[M]; // 优化,总是从当前弧 开始
int top;
int n,m;
void init()
{
top=0;
memset(head,-1,sizeof(head));
}
void addedge(int a,int b,int c)
{
Edge e={a,b,c,0,head[a]}; // 正向边
edge[top]=e;head[a]=top++;
Edge ee={b,a,0,0,head[b]}; //反向边
edge[top]=ee;head[b]=top++;
}
void getmap()
{
int a,b,c;
while(m--)
{
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
}
}
int bfs(int st,int ed) //得到残存的层次图
{
queue<int>Q;while(!Q.empty()) Q.pop();
memset(vis,0,sizeof(vis));
memset(dis,-1,sizeof(dis));
dis[st]=0;vis[st]=1;
Q.push(st);int now,nexts;
while(! Q.empty())
{
now=Q.front();Q.pop();
for(int i=head[now];i!=-1;i=edge[i].next)
{
Edge e=edge[i];
if(!vis[e.to]&&e.cap-e.flow>0)
{
vis[e.to]=1;
dis[e.to]=dis[now]+1;
if(e.to==ed) return 1; // 说明现在还有路到 终点
Q.push(e.to);
}
}
}
return 0;
}
int dfs(int now,int a,int ed) // 沿着bfs中找到的路径 将路上的 流量增大 ,
{
if(now==ed||a==0) return a;
int flow=0,f;
for(int& i=cur[now];i!=-1;i=edge[i].next)
{
Edge& e=edge[i];
if(dis[e.to]==dis[now]+1&&(f=dfs(e.to,min(e.cap-e.flow,a),ed))>0)
{
e.flow+=f;
edge[i^1].flow-=f; // 通过位运算来得到其反向边
flow+=f;
a-=f;
if(a==0) break;
}
}
return flow;
}
int max_flow(int st,int ed)
{
int flow=0;
while(bfs(st,ed)) // 如果还有路
{
memcpy(cur,head,sizeof(head));
flow+=dfs(st,inf,ed); // 不断增加的 每个边的流量直到 到达最大
}
return flow;
}
int main()
{
int k=1;
int t;scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
init();
getmap();
printf("Case %d: %d\n",k++,max_flow(1,n));
}
return 0;
}