Luogu P4553 80人环游世界

题目描述

https://www.luogu.com.cn/problem/P4553

Solution

注意到限制每个点被经过恰好 $a_i$ 次,所以我们考虑上下界

建图:

$s$ 连 $s’$,下界为 $0$,上界为 $m$,费用为 $0$

$s’$ 连 $u$,下界为 $0$,上界为 $m$,费用为 $0$

$u$ 连 $t$,下界为 $0$,上界为 $m$,费用为 $0$

$u$ 连 $u’$,下界为 $a_u$,上界为 $a_u$,费用为 $0$

$u’$ 连 $v$,下界为 $0$,上界为 $m$,费用为 $u$ 和 $v$ 的距离

跑有源汇上下界最小费用最大流即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <queue>
#define maxn 210
#define INF 1000000000
using namespace std;

int n, m, a[maxn];

struct Edge {
int to, next, w, fi;
} e[1000000]; int c1, head[maxn], in[maxn], out[maxn];
inline void add_edge(int u, int v, int w, int fi) {
e[c1].to = v; e[c1].w = w; e[c1].fi = fi;
e[c1].next = head[u]; head[u] = c1++;
}

inline void Add_edge(int u, int v, int l, int r, int fi) {
add_edge(u, v, r - l, fi); add_edge(v, u, 0, -fi);
in[v] += l; out[u] += l;
}

int la[maxn], pre[maxn], fl[maxn], dis[maxn], s, _s, t, ss, tt; bool vis[maxn];
bool spfa() {
fill(dis, dis + maxn, INF); dis[s] = 0;
queue<int> Q; Q.push(s); fl[s] = INF; pre[t] = -1;
while (!Q.empty()) {
int u = Q.front(); Q.pop(); vis[u] = 0;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w, fi = e[i].fi;
if (w > 0 && dis[v] > dis[u] + fi) {
dis[v] = dis[u] + fi; pre[v] = u;
fl[v] = min(fl[u], w); la[v] = i;
if (vis[v]) continue; vis[v] = 1;
Q.push(v);
}
}
}
return ~pre[t];
}

int mcmf() {
int mf = 0, mc = 0;
while (spfa()) {
mf += fl[t];
mc += fl[t] * dis[t];
int now = t;
while (now != s) {
e[la[now]].w -= fl[t];
e[la[now] ^ 1].w += fl[t];
now = pre[now];
}
}
return mc;
}

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m;
s = 0; _s = 2 * n + 1; t = _s + 1; ss = t + 1; tt = ss + 1;
Add_edge(s, _s, 0, m, 0);
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) {
Add_edge(_s, i, 0, m, 0);
Add_edge(i, i + n, a[i], a[i], 0);
Add_edge(i + n, t, 0, m, 0);
for (int j = i + 1; j <= n; ++j) {
int x; cin >> x;
if (~x) Add_edge(i + n, j, 0, m, x);
}
}
Add_edge(t, s, 0, INF, 0);
for (int i = s; i <= t; ++i) {
if (in[i] > out[i]) Add_edge(ss, i, 0, in[i] - out[i], 0);
else Add_edge(i, tt, 0, out[i] - in[i], 0);
}
swap(s, ss); swap(t, tt); int ans = mcmf(); swap(s, ss); swap(t, tt);
for (int i = head[s]; ~i; i = e[i].next)
if (e[i].to == t) e[i].w = e[i ^ 1].w = 0;
for (int i = head[ss]; ~i; i = e[i].next) e[i].w = e[i ^ 1].w = 0;
for (int i = head[tt]; ~i; i = e[i].next) e[i].w = e[i ^ 1].w = 0;
cout << ans + mcmf() << "\n";
return 0;
}