P9820 [ICPC2020 Shanghai R] Mine Sweeper II

Problem

Description

给出两张尺寸均为 \(n\times m\) 的扫雷地图 \(A,B\)。每次修改可以将一个地雷格改为非地雷格,或者将一个非地雷格改为地雷格。你可以修改最多 \(\lfloor \dfrac{nm}{2} \rfloor\) 个地图 \(B\) 中的格子,请给出一种方案,使得 \(A,B\) 中非地雷格上数字之和相同。若无解,输出 \(-1\)

Solution

简单来说,就是构造出两张图,差异在 \(\lfloor \dfrac{nm}{2} \rfloor\) 之内。

如果差异在 \(\lfloor \dfrac{nm}{2} \rfloor\) 之内,直接输出就好了。

对于其他情况,我们分析得出,如果把图返过来,一定满足两张图的差异在 \(\lfloor \dfrac{nm}{2} \rfloor\) 之内。

Code

#include <bits/stdc++.h>

using namespace std;

const int N = 1010;
char a[N][N], b[N][N];
int n, m;
int main() {
	ios::sync_with_stdio(false);
	cin >> n >> m;
	for (int i = 0; i < n; i++) cin >> a[i];
	for (int i = 0; i < n; i++) cin >> b[i];
	int c = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			c += (a[i][j] != b[i][j]); // 统计差异的次数
		}
	}
	if (c > (n * m >> 1)) { // 如果差异超过 n * m >> 1,将 A 改成反图
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (a[i][j] == '.') a[i][j] = 'X';
				else a[i][j] = '.';
			}
		}
	}
	for (int i = 0; i < n; i++) {
		cout << a[i] << endl;
	}
	return 0;
}
posted @ 2023-11-07 06:47  yhx0322  阅读(47)  评论(0)    收藏  举报