Problem DescriptionNetwork 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.
InputThe first line of input contains an integer T, denoting the number of test cases.
OutputFor each test cases, you should output the maximum flow from source 1 to sink N.
Sample Input2 3 2 1 2 1 2 3 1 3 3 1 2 1 2 3 1 1 3 1 Sample OutputCase 1: 1 Case 2: 2 最大流模板题。
|
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 20;
const int INF = 0x3f3f3f3f;
int pre[MAXN];
bool vis[MAXN];
int mp[MAXN][MAXN];
int s, e;
int n, m;
bool bfs() {
queue<int>q;
memset(pre, 0, sizeof(pre));
memset(vis, 0, sizeof(vis));
vis[s] = 1;
q.push(s);
while(!q.empty()) {
int first = q.front();
q.pop();
if(first == e) {
return true;
}
for(int i = 1; i <= n; i++) {
if(!vis[i] && mp[first][i]) {
q.push(i);
pre[i] = first;
vis[i] = 1;
}
}
}
return false;
}
int max_flow() {
int ans = 0;
while(true) {
if(!bfs()) {
return ans;
}
int Min = INF;
for(int i = e; i != s; i = pre[i]) {
Min = min(Min, mp[pre[i]][i]);
}
for(int i = e; i != s; i = pre[i]) {
mp[pre[i]][i] -= Min;
mp[i][pre[i]] += Min;
}
ans += Min;
}
return ans;
}
int main() {
int t;
scanf("%d", &t);
int u, v, c;
for(int i = 1; i <= t; i++) {
scanf("%d %d", &n, &m);
s = 1, e = n;
memset(mp, 0, sizeof(mp));
while(m--) {
scanf("%d %d %d", &u, &v, &c);
mp[u][v] += c;
}
printf("Case %d: %d\n", i, max_flow());
}
return 0;
}