Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4311 士兵占领

P4311 士兵占领

左部是行,连接源点,流量下界为该行需要的士兵数;同理,右部是列,连接汇点。对于可以放士兵的点,行和列中间连流量为 $1$ 的边,跑上下界最小流即可。

上下界网络流的处理办法:新建源汇点。对于流量盈余的点,将多余的流量连向新建汇点;对于流量不足的点,从新建源点向该点补上缺少的流量。原汇点向原源点连流量 $inf$ 的边。新建源点到新建汇点跑最大流,原汇点向原源点的边即原图的可行流。在此基础上,删去新建的边(只用删去最后原汇点向原源点的边即可),减去原图的 $t-s$ 的最大流即该图的上下界最小流;加上原图的 $s-t$ 的最大流即该图的上下界最大流。

查看代码
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <cstdio>
#include <queue>
using namespace std;
const int N = 210, M = 3e4 + 10, inf = 1e4;
bool block[N][N];
int n, m, K, st, ed, o[N], d[N], cur[N];
int idx = -1, hd[N], nxt[M], edg[M], wt[M];
bool bfs()
{
for (int i = 1; i <= ed; i++)
d[i] = -1;
d[st] = 0;
cur[st] = hd[st];
queue<int> q;
q.push(st);
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = hd[t]; ~i; i = nxt[i])
if (d[edg[i]] == -1 && wt[i])
{
cur[edg[i]] = hd[edg[i]];
d[edg[i]] = d[t] + 1;
if (edg[i] == ed)
return true;
q.push(edg[i]);
}
}
return false;
}
int exploit(int x, int limit)
{
if (x == ed)
return limit;
int res = 0;
for (int i = cur[x]; ~i && res < limit; i = nxt[i])
{
cur[x] = i;
if (d[edg[i]] == d[x] + 1 && wt[i])
{
int t = exploit(edg[i], min(wt[i], limit - res));
if (!t)
d[edg[i]] = -1;
wt[i] -= t;
wt[i ^ 1] += t;
res += t;
}
}
return res;
}
int dinic()
{
int res = 0, flow;
while (bfs())
while (flow = exploit(st, inf))
res += flow;
return res;
}
void add(int a, int b, int c)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
wt[idx] = c;
}
int main()
{
scanf("%d%d%d", &n, &m, &K);
int s, t;
s = n + m + 1, t = s + 1, st = s + 2, ed = t + 2;
for (int i = 1; i <= ed; i++)
hd[i] = -1;
for (int i = 1, a; i <= n; i++)
{
scanf("%d", &a);
add(s, i, inf);
add(i, s, 0);
o[s] -= a;
o[i] += a;
}
for (int i = n + 1, a; i < s; i++)
{
scanf("%d", &a);
add(i, t, inf);
add(t, i, 0);
o[i] -= a;
o[t] += a;
}
for (int a, b; K; K--)
{
scanf("%d%d", &a, &b);
block[a][b] = true;
}
for (int i = 1; i <= n; i++)
for (int j = n + 1; j < s; j++)
if (!block[i][j - n])
{
add(i, j, 1);
add(j, i, 0);
}
int tot = 0;
for (int i = 1; i <= t; i++)
if (o[i] > 0)
{
add(st, i, o[i]);
add(i, st, 0);
tot += o[i];
}
else if (o[i] < 0)
{
add(i, ed, -o[i]);
add(ed, i, 0);
}
add(t, s, inf);
add(s, t, 0);
if (dinic() < tot)
{
puts("JIONG");
return 0;
}
int res = wt[idx];
wt[idx] = wt[idx - 1] = 0;
st = t, ed = s;
printf("%d", res - dinic());
return 0;
}