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
思路
最大流模板题,三大算法都能过。好久没用链式前向星写题了,贴个模板纪念一下。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <cmath>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
struct edge{
int to;
int next;
int w;
}e[maxn<<1];
int head[20];
int dep[20];
int tot;
void addedge(int x,int y,int z)
{
e[tot].to = y;
e[tot].w = z;
e[tot].next = head[x];
head[x] = tot++;
}
int bfs(int s,int t)
{
memset(dep,0,sizeof(dep));
queue<int>q;
q.push(s);dep[s] = 1;
while(!q.empty()){
int x = q.front();
q.pop();
for(int i = head[x];~i;i = e[i].next){
if(e[i].w && !dep[e[i].to]){
dep[e[i].to] = dep[x] + 1;
q.push(e[i].to);
}
}
}
return dep[t];
}
int dfs(int s,int flow,int t)
{
if(s == t) return flow;
int sum = 0;
for(int i = head[s];~i;i = e[i].next){
if(e[i].w && dep[e[i].to] == dep[s]+1){
int k = dfs(e[i].to,min(flow-sum,e[i].w),t);
if(k){
e[i].w -= k;
e[i^1].w += k;
sum += k;
if(sum == flow) break;
}
}
}
if(!sum) dep[s] = -1; //炸点
return sum;
}
int Dinic(int s,int t)
{
int sum = 0;
while(bfs(s,t)){
sum += dfs(s,inf,t);
}
return sum;
}
int main()
{
int t,n,m;
scanf("%d",&t);
for(int k = 1;k <= t;k++){
tot = 0;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i = 0;i < m;i++){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z); addedge(y,x,0);
}
int sum = Dinic(1,n);
printf("Case %d: %d\n",k,sum);
}
return 0;
}
愿你走出半生,归来仍是少年~