对于一个标记位置,其周围四联通的格子都可以考虑覆盖。
若干个标记位置形成的覆盖区域可能会有重叠,形成联通块。容易发现我们只需将每个联通块的结果合并起来,就可以得到整个问题的解。
对于每个联通块,设该块内标记格有 格,非标记格有 格,容易发现有三种情况:
- ,此时一定不存在一种合法方案(因为覆盖一个标记格,需要相应覆盖三个非标记格);
- ,此时存在一种方案,使得联通块内所有格子均被覆盖。
- (事实上这时候一定有 ,因为 个标记格的覆盖区域内一定存在至少 个重叠格,故非标记格的上限为 ),和情况 类似,只不过这时候多了一个格子,因此只需贪心删去联通块内权值最小的非标记格即可。
维护联通性可以通过并查集实现。
// Problem: P6234 [eJOI2019]T形覆盖
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P6234
// Memory Limit: 100 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <algorithm>
#include <iostream>
using namespace std;
const int maxs = 1000005;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
int a[1000005], vis[1000005], m, n, k;
int id(int x, int y) { return x * n + y; }
struct point {
int x, y;
} p[1000005];
struct dsu {
int fa[maxs], sum[maxs], mina[maxs], cnt1[maxs], cnt2[maxs];
void init(int m, int n) {
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
int pos = id(i, j);
sum[pos] = mina[pos] = a[pos];
fa[pos] = pos;
cnt1[pos] = 1;
}
for (int i = 1; i <= k; i++) {
int pos = id(p[i].x, p[i].y);
cnt1[pos] = 0;
cnt2[pos] = 1;
mina[pos] = 1e9;
}
}
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
x = find(x), y = find(y);
if (x == y) return;
fa[y] = x;
cnt1[x] += cnt1[y];
cnt2[x] += cnt2[y];
sum[x] += sum[y];
mina[x] = min(mina[x], mina[y]);
}
} se;
int main() {
cin >> m >> n;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) cin >> a[id(i, j)];
cin >> k;
for (int i = 1; i <= k; i++) cin >> p[i].x >> p[i].y;
se.init(m, n);
for (int i = 1; i <= k; i++) {
int x = p[i].x, y = p[i].y;
for (int j = 0; j <= 3; j++) {
int nx = x + dx[j], ny = y + dy[j];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
se.merge(id(x, y), id(nx, ny));
}
}
int ans = 0;
for (int i = 1; i <= k; i++) {
int pos = se.find(id(p[i].x, p[i].y));
if (vis[pos]) continue;
if (se.cnt1[pos] < 3 * se.cnt2[pos]) {
cout << "No" << endl;
return 0;
} else if (se.cnt1[pos] == 3 * se.cnt2[pos])
ans += se.sum[pos];
else // se.cnt1[pos] == 3 * se.cnt2[pos] + 1
ans += se.sum[pos] - se.mina[pos];
vis[pos] = 1;
}
cout << ans << endl;
return 0;
}