#include <bits/stdc++.h>
#define ll long long
using namespace std;
int n, m, s ,t, tot;
const int N = 5010, M = 500005, inf = 1 << 29;
long long maxflow = 0, ans = 0;
int ver[M], edge[M], cost[M], Next[M], Head[N];
int d[N], incf[N], pre[N], v[N];
int a[105], b[105], c[105][105];
void add(int x, int y, int z, int c) {
// 正向边,初始容量z,单位费用c
ver[++tot] = y, edge[tot] = z, cost[tot] = c;
Next[tot] = Head[x], Head[x] = tot;
// 反向边,初始容量0,单位费用-c,与正向边“成对存储”
ver[++tot] = x, edge[tot] = 0, cost[tot] = -c;
Next[tot] = Head[y], Head[y] = tot;
}
bool spfa() {
queue<int> q;
memset(d, 0x3f, sizeof(d));
memset(v, 0, sizeof(v));
//memset(incf, 0x7f, sizeof(incf));
q.push(s); d[s] = 0; v[s] = 1; pre[t] = -1; // SPFA 求最长路
incf[s] = 1 << 30; // 增广路上各边的最小剩余容量
while (q.size()) {
int x = q.front();
q.pop();
v[x] = 0;
for (int i = Head[x]; i; i = Next[i]) {
if (!edge[i]) continue; // 剩余容量为0,不在残量网络中,不遍历
int y = ver[i];
if (d[y] > d[x] + cost[i]) {
d[y] = d[x] + cost[i];
incf[y] = min(incf[x], edge[i]);
pre[y] = i; // 记录前驱,便于找到最长路的实际方案
if (!v[y]) v[y] = 1, q.push(y);
}
}
}
return pre[t] != -1;// 汇点不可达,已求出最大流
}
bool spfa1() {
queue<int> q;
memset(d, 0xcf, sizeof(d)); // -INF
memset(v, 0, sizeof(v));
q.push(s); d[s] = 0; v[s] = 1; pre[t] = -1; // SPFA 求最长路
incf[s] = 1 << 30; // 增广路上各边的最小剩余容量
while (q.size()) {
int x = q.front();
q.pop();
v[x] = 0;
for (int i = Head[x]; i; i = Next[i]) {
if (!edge[i]) continue; // 剩余容量为0,不在残量网络中,不遍历
int y = ver[i];
if (d[y] < d[x] + cost[i]) {
d[y] = d[x] + cost[i];
incf[y] = min(incf[x], edge[i]);
pre[y] = i; // 记录前驱,便于找到最长路的实际方案
if (!v[y]) v[y] = 1, q.push(y);
}
}
}
return pre[t] != -1;// 汇点不可达,已求出最大流
}
//更新最长增广路及其反向边的剩余容量
int update() {
int x = t;
while (x != s) {
int i = pre[x];
edge[i] -= incf[t];
edge[i ^ 1] += incf[t]; // 利用“成对存储”的xor 1技巧
x = ver[i ^ 1];
}
return d[t] * incf[t];
}
void init() {
memset(Head, 0, sizeof(Head));
tot = 1;
s = n + m + 1;
t = s + 1;
for (int i = 1; i <= m; i++) add(s, i, a[i], 0);
for (int j = 1; j <= n; j++) add(j + m, t, b[j], 0);
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
add(i, j + m, inf, c[i][j]);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> m >> n;
tot = 1;
s = m + n + 1;
t = s + 1;
for (int i = 1; i <= m; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> c[i][j];
}
}
long long ans1 = 0, ans2 = 0;
init();
while (spfa()) ans1 += update();
init();
while (spfa1()) ans2 += update();
cout << ans1 << '\n' << ans2;
return 0;
}
洛谷 P4015 运输问题 题解
最新推荐文章于 2022-11-12 19:27:17 发布