您的位置:首页 > 其它

集训队专题(7)1002 Flow Problem

2016-02-27 16:12 274 查看


Flow Problem

Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)

Total Submission(s): 12028 Accepted Submission(s): 5705



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)

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


Author

HyperHexagon

Source

HyperHexagon's Summer Gift (Original tasks)

此题也属于基础的网络流最大流问题,同样只需要用到最简单的EK算法,EK算法的思想务必需要掌握,不能一味的只是套模板,之后的Dinic算法也是基于EK算法的思想上的。

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1000+2;
const int INF = 0xfffffff;
int capacity[maxn][maxn],flow[maxn],pre[maxn],n,m;
queue<int> q;
int BFS(int src,int des)
{
int i,j;
while(!q.empty())
q.pop();
for(int i=1; i<=m; i++) pre[i] = -1;
pre[src] = 0;
flow[src] = INF;
q.push(src);
while(!q.empty())
{
int index = q.front();
q.pop();
if(index == des) break;
for(i=1; i<=m; i++)
{
if(i!=src && capacity[index][i]>0 && pre[i]==-1)
{
pre[i] = index;
flow[i] = min(flow[index],capacity[index][i]);
q.push(i);
}
}
}
if(pre[des] == -1) return -1;
else return flow[des];
}
int maxFlow(int src,int des)
{
int increasement = 0;
int sumflow = 0;
while((increasement = BFS(1,m)) != -1)
{
int k = des;
while(k != src)
{
int last = pre[k];
capacity[last][k] -= increasement;
capacity[k][last] += increasement;
k = last;
}
sumflow += increasement;
}
return sumflow;
}
int main()
{
int t,start,end,ci,Case=1;
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
memset(capacity,0,sizeof(capacity));
memset(flow,0,sizeof(flow));
scanf("%d%d",&m,&n);
for(int i=1; i<=n; i++)
{
scanf("%d%d%d",&start,&end,&ci);
if(start == end) continue;
capacity[start][end] += ci;
}
printf("Case %d: %d\n",Case++,maxFlow(1,m));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: