【思路要点】
- 为每条边附加一个 1 1 1 的费用,问题等价于原图上的最大费用循环流。
- 不妨假设所有边都已经流满,将所有边反向,记 d i d_i di 表示原图中点 i i i 出度减入度的差,若 d i d_i di 大于 0 0 0 ,则将 i i i 连向汇点,容量为 d i d_i di ,否则将源点连向 i i i ,容量为 − d i -d_i −di 。
- 新图上的最小费用最大流的费用就代表了为了保证流量平衡在原图中需要损失的费用,在原图的边权和中减去这个费用即可。
- 时间复杂度 O ( M i n i m u m C o s t F l o w ( N , N + M ) ) O(MinimumCostFlow(N,N+M)) O(MinimumCostFlow(N,N+M)) 。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 4005; const int MAXQ = 1e7 + 5; const int INF = 1e9; typedef long long ll; typedef long double ld; typedef unsigned long long ull; template <typename T> void chkmax(T &x, T y) {x = max(x, y); } template <typename T> void chkmin(T &x, T y) {x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } struct edge {int dest, flow; unsigned pos; int cost; }; vector <edge> a[MAXN]; int n, m, s, t, flow, cost, ans; int dist[MAXN], path[MAXN], home[MAXN], d[MAXN]; void FlowPath() { int p = t, ans = INF; while (p != s) { ans = min(ans, a[path[p]][home[p]].flow); p = path[p]; } flow += ans; cost += ans * dist[t]; p = t; while (p != s) { a[path[p]][home[p]].flow -= ans; a[p][a[path[p]][home[p]].pos].flow += ans; p = path[p]; } } bool spfa() { static int q[MAXQ]; static bool inq[MAXN]; static int l = 0, r = 0; for (int i = 0; i <= r; i++) dist[q[i]] = INF; q[l = r = 0] = s, dist[s] = 0, inq[s] = true; while (l <= r) { int tmp = q[l++]; for (unsigned i = 0; i < a[tmp].size(); i++) if (a[tmp][i].flow != 0 && dist[tmp] + a[tmp][i].cost < dist[a[tmp][i].dest]) { dist[a[tmp][i].dest] = dist[tmp] + a[tmp][i].cost; path[a[tmp][i].dest] = tmp; home[a[tmp][i].dest] = i; if (!inq[a[tmp][i].dest]) { q[++r] = a[tmp][i].dest; inq[q[r]] = true; } } inq[tmp] = false; } return dist[t] != INF; } void addedge(int x, int y, int z, int c) { a[x].push_back((edge) {y, z, a[y].size(), c}); a[y].push_back((edge) {x, 0, a[x].size() - 1, -c}); } int main() { read(n), read(m); for (int i = 1; i <= m; i++) { int x, y, z; read(x), read(y), read(z); addedge(y, x, z, 1); d[x] += z, d[y] -= z; ans += z; } s = 0, t = 2 * n + 1; for (int i = 1; i <= n; i++) { if (d[i] > 0) addedge(i, t, d[i], 0); if (d[i] < 0) addedge(s, i, -d[i], 0); } for (int i = s; i <= t; i++) dist[i] = INF; while (spfa()) FlowPath(); writeln(ans - cost); return 0; }