这题也是高斯消元的模板题,要枚举自由变元求得最优解。也可以直接暴力枚举,不过有技巧的是,只需要第一行枚举下,每行得到使得该行以上可以的状态,然后继续往下枚举。
我是感觉直接高斯消元还简单明了点~
// 高斯消元解异或方程组 poj 1753
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[22][22], x[22], var, equ, n, pos[22];
char s[22][22];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
void init(int q) {
memset(a, 0, sizeof(a));
equ = var = n*n;
for(int i = 0;i < n; i++) {
for(int j = 0;j < n; j++) {
int st = i*n+j;
if(s[i][j] == 'w')
a[st][var] = q;
else
a[st][var] = !q;
a[st][st] = 1;
for(int k = 0;k < 4; k++) {
int xx = i+dir[k][0];
int yy = j+dir[k][1];
if(xx < 0 || xx >= n || yy < 0 || yy >= n)
continue;
int to = xx*n+yy;
a[st][to] = 1;
}
}
}
}
int min_sum;
void dfs(int row, int col) {
if(col == -1 && row == -1) {
int sum = 0;
for(int i = 0;i < var; i++) sum += x[i];
min_sum = min(min_sum, sum);
return ;
}
if(pos[row] == col) {
x[col] = a[row][var];
for(int i = var-1;i > col; i--) x[col] ^= x[i]&a[row][i];
dfs(row-1, col-1);
}
else {
x[col] = 1; dfs(row, col-1);
x[col] = 0; dfs(row, col-1);
}
}
int gauss() {
int row = 0, col = 0;
for( ; row < equ && col < var; row++, col++) {
int maxr = row;
for(int i = row+1;i < equ; i++) if(a[i][col])
maxr = i;
if(a[maxr][col] == 0) {
row--; continue;
}
if(row != maxr) {
for(int i = col;i < var+1; i++)
swap(a[maxr][i], a[row][i]);
}
for(int i = row+1;i < equ; i++) {
if(a[i][col]==0) continue;
for(int j = col;j < var+1; j++)
a[i][j] ^= a[row][j];
}
}
// 无解
for(int i = row;i < equ; i++) if(a[i][var])
return -1;
if(row < var) {
// 多解情况,求最小解
min_sum = 1<<30;
for(int i = 0;i < row; i++) {
for(int j = 0;j < var; j++) if(a[i][j]) {
pos[i] = j; break;
}
}
dfs(row-1, var-1);
return min_sum;
}
// 唯一解
int ans = 0;
for(int i = var-1;i >= 0; i--) {
x[i] = a[i][var];
for(int j = i+1;j < var; j++)
x[i] ^= x[j]&a[i][j];
ans += x[i];
}
return ans;
}
int main() {
n = 4;
for(int i = 0;i < n; i++)
scanf("%s", s[i]);
init(0);
int ans1 = gauss();
init(1);
int ans2 = gauss();
if(ans1 == -1 && ans2 == -1)
puts("Impossible");
else if(ans1 == -1)
printf("%d\n", ans2);
else if(ans2 == -1)
printf("%d\n", ans1);
else
printf("%d\n", min(ans1, ans2));
}