题意
这是一个模板,求网络最大流。
思路
d i n i c dinic dinic算法。在残量网络中建分层图, d f s dfs dfs寻找增广路。
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
const int inf = 1 << 29, N = 10001, M = 100001;
int n, m, s, t, tot = 1;
int edge[M * 2], head[N], next[M * 2], ver[M * 2], dep[N];
std::queue<int> q;
void add(int x, int y, int z) {
ver[++tot] = y;
edge[tot] = z;
next[tot] = head[x];
head[x] = tot;
ver[++tot] = x;
edge[tot] = 0;
next[tot] = head[y];
head[y] = tot;
}
bool bfs(int st, int en) {
memset(dep, 0, sizeof(dep));
while (q.size()) q.pop();
q.push(st);
dep[st] = 1;
while (q.size()) {
int x = q.front();
q.pop();
for (int i = head[x]; i; i = next[i]) {
if (edge[i] && !dep[ver[i]]) {
q.push(ver[i]);
dep[ver[i]] = dep[x] + 1;
if (ver[i] == en) return 1;
}
}
}
return 0;
}
int dfs(int x, int en, int flow) {
if (x == en) return flow;
int rest = flow, k;
for (int i = head[x]; i && rest; i = next[i])
if (edge[i] && dep[ver[i]] == dep[x] + 1) {
k = dfs(ver[i], en, std::min(rest, edge[i]));
if (!k) dep[ver[i]] = 0;
edge[i] -= k;
edge[i ^ 1] += k;
rest -= k;
}
return flow - rest;
}
int dinic(int st, int en) {
int res = 0, flow = 0;
while (bfs(st, en))
while (flow = dfs(st, en, inf)) res += flow;
return res;
}
int main() {
scanf("%d %d %d %d", &n, &m, &s, &t);
int x, y, z;
for (int i = 1; i <= m; i++) {
scanf("%d %d %d", &x, &y, &z);
add(x, y, z);
}
printf("%d", dinic(s, t));
}