Flow Problem
Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 10338 Accepted Submission(s): 4871
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)
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 <iostream>
#include <algorithm>
#include <queue>
#define maxn 100 + 10
#define maxm 2000 + 200
#define INF 0x3f3f3f3f
using namespace std;
int cnt, n, m;
int dist[maxn];
int cur[maxn], vis[maxn];
int head[maxn];
struct node{
int u, v, cap, flow, next;//cap 最大流量, flow 当前流量
};
node edge[maxm];
void init(){
cnt = 0;
memset(head, -1, sizeof(head));
}
void add(int u, int v, int w){
edge[cnt] = {u, v, w, 0, head[u]};//正建边
head[u] = cnt++;
edge[cnt] = {v, u, 0, 0, head[v]};//反建边
head[v] = cnt++;
}
void getmap(){
int u ,v, w;
while(m--){
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
return ;
}
bool BFS(int st, int ed){
queue<int>q;
memset(dist, -1, sizeof(dist));
memset(vis, 0, sizeof(vis));
dist[st] = 0;
vis[st] = 1;
q.push(st);
while(!q.empty()){
int u = q.front();
q.pop();
for(int i = head[u]; i != -1; i = edge[i].next){
node E = edge[i];
if(!vis[E.v] && E.cap > E.flow){
vis[E.v] = 1;
dist[E.v] = dist[u] + 1; //建立层次图
if(E.v == ed) return true; //一条可以从源点到汇点的最短路径
q.push(E.v);
}
}
}
return false;
}
int DFS(int x, int ed, int a){ //把找到的这个路径上所有的边的当前流量都增加a
if(x == ed || a == 0) //(a是所找出路径的边中 残余流量的最小值)
return a;
int flow = 0, f;
for(int& i = cur[x]; i != -1; i = edge[i].next){//从上次考虑的弧开始
node& E = edge[i];
if(dist[E.v] == dist[x] + 1 && (f = DFS(E.v, ed, min(a, E.cap - E.flow))) > 0){
E.flow += f;//正向边
edge[i ^ 1].flow -= f;//反向边
flow += f;//总流量
a -= f;
if(a == 0) break;
}
}
return flow;
}
int maxflow(int st, int ed){
int flow = 0;
while(BFS(st, ed)){
memcpy(cur, head, sizeof(head));
flow += DFS(st, ed, INF);
}
return flow;
}
int main (){
int T;
int k = 1;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
init();
getmap();
printf("Case %d: %d\n", k++, maxflow(1, n));
}
return 0;
}