POJ 1753 Flip Game 高斯消元
先用高斯消元化简,然后枚举自由变元
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <climits>
#include <iostream>
#include <string>
using namespace std;
#define MP make_pair
#define PB push_back
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
const int INF = INT_MAX / 3;
const double eps = 1e-8;
const LL LINF = 1e17;
const double DINF = 1e60;
const int maxn = 250;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
int a[maxn][maxn], n;
bool fx[maxn];
char buf[16][16];
void Gauss() {
for(int i = 0; i < n * n; i++) {
int k = i;
while(a[k][i] == 0 && k < n * n) k++;
if(k >= n * n) break;
for(int j = 0; j <= n * n; j++) swap(a[i][j], a[k][j]);
for(int j = 0; j < n * n; j++) if(j != i && a[j][i] != 0) {
for(int k = 0; k <= n * n; k++) {
a[j][k] ^= a[i][k];
}
}
}
}
void pp() {
for(int i = 0; i < n * n; i++) {
for(int j = 0; j <= n * n; j++) {
printf("%d ", a[i][j]);
}
puts("");
}
}
int solve() {
memset(a, 0, sizeof(a));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(buf[i][j] == 'w') a[i * n + j][n * n] = 1;
else a[i * n + j][n * n] = 0;
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int u = i * n + j;
a[u][u] = 1;
for(int k = 0; k < 4; k++) {
int nx = i + dx[k], ny = j + dy[k], nu = nx * n + ny;
if(nx >= 0 && nx < n && ny >= 0 && ny < n) {
a[u][nu] = a[nu][u] = 1;
}
}
}
}
Gauss();
memset(fx, 0, sizeof(fx));
int ans = INF, fcnt = 0;
bool bad = false;
for(int i = 0; i < n * n; i++) {
int nsum = 0;
for(int j = 0; j < n * n; j++) nsum += a[i][j];
if(nsum == 0 && a[i][n * n] == 1) bad = true;
if(nsum == 0) fx[i] = true, fcnt++;
}
if(bad) return INF;
for(int s = 0; s < (1 << fcnt); s++) {
int nowans = 0;
for(int i = 0; i < n * n - fcnt; i++) {
int col = 0;
for(int j = 0; j < n * n; j++) if(fx[j] && a[i][j]) {
if(s & (1 << (n * n - j - 1))) col ^= 1;
}
if(a[i][n * n] != col) nowans++;
}
int bcnt = 0;
for(int i = 0; i < fcnt; i++) if(s & (1 << i)) bcnt++;
ans = min(nowans + bcnt, ans);
}
return ans;
}
int main() {
while(scanf("%s%s%s%s", buf[0], buf[1], buf[2], buf[3]) != EOF) {
n = 4;
int ans = solve();
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(buf[i][j] == 'w') buf[i][j] = 'b';
else buf[i][j] = 'w';
}
}
ans = min(ans, solve());
if(ans < INF) printf("%d\n", ans);
else puts("Impossible");
}
return 0;
}

浙公网安备 33010602011771号