题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=3549
前几天比赛发现自己的最大流最小割知识忘的一干二尽竟是一朝回到解放前,于是重新学习最大流。EK算法,其实就是BFS求增广路,增广条件是向前的边或是未满的正向边或是大于0的反向边,这样每次增广必然可以让t节点获得值增加
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 20;
const int INF = 0x3f3f3f3f;
int n, m;
struct Edge
{
int from, to, cap, flow;
Edge(int from, int to, int cap, int flow):from(from), to(to), cap(cap), flow(flow){}
};
struct EdmondsKarp
{
vector<Edge> edges;
vector<int>G[maxn];
int a[maxn];
int p[maxn];
void init(int n)
{
for(int i = 0;i < n;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap)
{
edges.push_back(Edge(from, to, cap, 0));
edges.push_back(Edge(to, from, 0, 0));
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
int Maxflow(int s, int t)
{
int flow = 0;
for(;;)
{
memset(a, 0, sizeof(a));
queue<int>Q;
Q.push(s);
a[s] = INF;
while(!Q.empty())
{
int x = Q.front();
Q.pop();
for(int i = 0;i < (int)G[x].size();i++)
{
Edge &e = edges[G[x][i]];
if(!a[e.to]&&e.cap > e.flow)
{
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap - e.flow);
Q.push(e.to);
}
}
if(a[t])
break;
}
if(!a[t])
break;
for(int u = t;u != s;u = edges[p[u]].from)
{
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
}
flow += a[t];
}
return flow;
}
}ek;
int main()
{
int t;
scanf("%d", &t);
int kase = 1;
while(t--)
{
scanf("%d%d", &n, &m);
ek.init(n);
for(int i = 1;i <= m;i++)
{
int a, b, c;
cin>>a>>b>>c;
a--;
b--;
ek.AddEdge(a, b, c);
}
cout<<"Case "<<kase++<<": "<<ek.Maxflow(0, n - 1)<<endl;
}
return 0;
}