Luogu P1935 [国家集训队]圈地计划

题目描述

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

简要题意:现在有一个 $n\times m$ 的四连通网格,每个位置填 $0$ 有 $a_{i,j}$ 的收益,填 $1$ 有 $b_{i,j}$ 的收益,对于每个格子 $(i,j)$ 如果它周围的格子中有 $k$ 个格子和它填的数不同,那么会有 $k\times c_{i,j}$ 收益,求最大收益

$n,m\le 100$

Solution

注意到当两个位置所选区域不同可以获得收益,且为二分图

所以我们直接考虑将二分图两部分与 $s,t$ 的关系反过来即可

建图:

对于白点 $(i,j)$, $s$ 连 $(i,j)$,容量为 $a_{i,j}$

$(i,j)$ 连 $t$,容量为 $b_{i,j}$

对于黑点 $(i,j)$,$s$ 连 $(i,j)$,容量为 $b_{i,j}$

$(i,j)$ 连 $t$,容量为 $a_{i,j}$

对于 $(i,j)$,$(i,j)$ 连相邻的点,容量为 $c_{i,j}$,注意为双向边

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
#include <iostream>
#include <cstdio>
#include <queue>
#define maxn 10010
#define maxm 110
#define INF 1000000000
using namespace std;

int dx[] = { 1, -1, 0, 0 };
int dy[] = { 0, 0, 1, -1 };

int n, m, s, t;

int a[maxm][maxm], b[maxm][maxm], c[maxm][maxm];

inline int D(int x, int y) { return (x - 1) * m + y; }

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

inline void Add_edge(int u, int v, int w) {
add_edge(u, v, w); add_edge(v, u, 0);
}

int dep[maxn];
bool bfs() {
fill(dep, dep + maxn, 0); dep[s] = 1;
queue<int> Q; Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (!dep[v] && w > 0) {
dep[v] = dep[u] + 1;
Q.push(v); if (v == t) return 1;
}
}
}
return 0;
}

int dfs(int u, int _w) {
if (u == t || !_w) return _w;
int s = 0;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (w > 0 && dep[v] == dep[u] + 1) {
int di = dfs(v, min(_w - s, w));
e[i].w -= di; e[i ^ 1].w += di;
s += di; if (s == _w) break;
}
}
if (s < _w) dep[u] = 0;
return s;
}

int dinic() {
int mf = 0;
while (bfs()) mf += dfs(s, INF);
return mf;
}

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

cin >> n >> m; s = 0; t = n * m + 1;
int ans = 0;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) cin >> a[i][j];
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) cin >> b[i][j];
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) cin >> c[i][j];
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
int id = D(i, j);
if (i + j & 1) Add_edge(s, id, a[i][j]), Add_edge(id, t, b[i][j]);
else Add_edge(s, id, b[i][j]), Add_edge(id, t, a[i][j]);
ans += a[i][j] + b[i][j];
for (int k = 0; k < 4; ++k) {
int x = i + dx[k], y = j + dy[k];
if (x < 1 || x > n || y < 1 || y > m) continue;
Add_edge(id, D(x, y), c[i][j]);
Add_edge(D(x, y), id, c[i][j]);
ans += c[i][j];
}
}
cout << ans - dinic() << "\n";
return 0;
}