保存一份最大流模板
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1532
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 405; //這裏如果是邊的話,記得要乘2,因爲有反向邊,不然會有re
const int inf = 0x3f3f3f3f;//這裏可以處理重邊的情況
struct edge
{
int u, v, c, f, next;
} e[maxn];
int head[maxn], cnt;
void init()
{
cnt = 0;
memset(head, -1, sizeof(head));
}
void addedge(int u, int v, int c)
{
e[cnt].u = u, e[cnt].v = v, e[cnt].f = 0, e[cnt].c = c, e[cnt].next = head[u], head[u] = cnt++;
e[cnt].u = v, e[cnt].v = u, e[cnt].f = 0, e[cnt].c = 0, e[cnt].next = head[v], head[v] = cnt++;
}
struct Dinic
{
int s, t;
bool vis[maxn];
int d[maxn];
bool bfs()
{
memset(vis, false, sizeof(vis));
queue<int> q;
q.push(s);
vis[s] = true;
while(!q.empty())
{
int u= q.front();
q.pop();
for(int i = head[u]; i != -1; i = e[i].next)
{
edge &f = e[i];
if(!vis[f.v] && f.c > f.f)
{
vis[f.v] = true;
d[f.v] = d[u] + 1;
q.push(f.v);
}
}
}
return vis[t];
}
int dfs(int x, int a)
{
if(x == t || a == 0) return a;
int flow = 0, ans;
for(int i = head[x]; i != -1; i = e[i].next)
{
edge &f = e[i];
if(d[f.v] == d[x] + 1 && (ans = dfs(f.v, min(a, f.c - f.f))) > 0)
{
f.f += ans;
e[i ^ 1] .f -= ans;
flow += ans;
a -= ans;
if(a == 0)
break;
}
}
return flow;
}
int maxflow(int s, int t)
{
this->s = s, this->t = t;
int flow = 0;
while(bfs())
flow += dfs(s, inf);
return flow;
}
};
Dinic d;
int main()
{
int n, m;
while(~scanf("%d%d", &n, &m))
{
init();
for(int i = 0; i < n; i++)
{
int u, v, c;
scanf("%d%d%d", &u, &v, &c);
addedge(u, v, c);
}
int ans = d.maxflow(1, m);
printf("%d\n", ans);
}
return 0;
}