题意
n n n个点, m m m条边,每条边 e e e 有一个流量下界lower(e)和流量上界upper(e),给定源点 s s s与汇点 t t t,求源点到汇点的最小流。
思路
同求有上下界最大流的方法,先求出有源汇有上下界的可行流。
在网络流的算法中, u − v u-v u−v这条边的流量增加等于 v − u v-u v−u流量减少,所以我们可以从 t t t向 s s s跑最大流,找出一条可行流,相当于顺着从这条路上减去那么多流量。( t − s t-s t−s最大流其实是尽量缩减 s − t s-t s−t方向的流)。
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
const int inf = 1 << 29, N = 50010, M = 125010;
int n, m, s, t, lower, upper, ss, tt, tot = 1;
int edge[(N + M) * 2], head[N], next[(N + M) * 2], ver[(N + M) * 2], dep[N], d[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);
for (int i = 1; i <= m; i++) {
scanf("%d %d %d %d", &ss, &tt, &lower, &upper);
d[ss] -= lower;
d[tt] += lower;
add(ss, tt, upper - lower);
}
ss = 0;
tt = n + 1;
int all = 0;
for (int i = 1; i <= n; i++) {
if (d[i] > 0) add(ss, i, d[i]), all += d[i];
else add(i, tt, -d[i]);
}
add(t, s, inf);
int flow = 0, maxflow = 0;
if (dinic(ss, tt) != all) {
printf("please go home to sleep");
return 0;
}
maxflow = edge[tot];
edge[tot] = edge[tot ^ 1] = 0;
printf("%d", maxflow - dinic(t, s));
}