C2. Errich-Tac-Toe (Hard Version)
Question: Give a matrix with k'X' or'O' marks, and now you need to modify no more than k / 3 marks ('X' is changed to'O','O' is changed to'X'), So that there are no three consecutive identical marks in the matrix
Idea: Modify the position of (i + j)% 3 == opx and (i + j)% 3 == opo separately for two different tags, provided that the number of modifications is less than one-third of the total number of tags One, so enumerate opx and opo, and then determine whether it is legal
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const double eps = 1e-8;
const double PI = acos(-1.0);
const int N = 310;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
char s[N][N];
int main() {
int t, n;
scanf("%d", &t);
while(t--) {
int xx = 0, oo = 0;
scanf("%d", &n);
int x[3] = {0, 0, 0}, o[3] = {0, 0, 0};
for(int i = 0; i < n; ++i) scanf("%s", &s[i]);
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(s[i][j] == 'X') xx++, x[(i + j) % 3]++;
else if(s[i][j] == 'O') oo++, o[(i + j) % 3]++;
}
}
int opx = -1, opo = -1;
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
if(i == j) continue;
if(x[i] + o[j] <= (xx + oo) / 3) {
opx = i, opo = j;
break;
}
}
if(opx != -1) break;
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(s[i][j] == 'X' && (i + j) % 3 == opx) cout << 'O';
else if(s[i][j] == 'O' && (i + j) % 3 == opo) cout << 'X';
else cout << s[i][j];
}
cout<<'\n';
}
}
}