题目链接:http://poj.org/problem?id=1681
和POJ 1753 一样
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 400,INF = 0x3f3f3f3f;
typedef int Matrix[maxn][maxn];
const int step[][2] = { {0,0} , {-1,0} , {1,0} , {0,1} , {0,-1} };
Matrix A;
int ANS[maxn],n;
void init(){
memset(A,0,sizeof A);
int i,j,k,c_pos,n_pos,cx,cy,nx,ny;
for(i = 0;i < n;++i){
for(j = 0;j < n;++j){
c_pos = i * n + j;
for(k = 0;k < 5;++k){
nx = i + step[k][0],ny = j + step[k][1];
if(nx >= 0 && nx < n && ny >= 0 && ny < n){
A[nx * n + ny][c_pos] = 1;
}
}
}
}
}
int Gauss(Matrix A,int n){
int i,j,k,p;
for(i = j = 0;j < n && i < n;++j){
k = i;
for(p = i + 1;p < n;++p) if(A[p][j] > A[k][j]) k = p;
if(A[k][j]){
for(p = 0;p <= n;++p) swap(A[i][p],A[k][p]);
for(k = i + 1;k < n;++k){
if(A[k][j]){
for(p = j;p <= n;++p) A[k][p] = (A[k][p] - A[i][p] + 2) % 2;
}
}
i++;
}
}
for(k = i;k < n;++k) if(A[k][n]) return INF;
int cnt = n - i,minAns = INF,tmpAns;
for(int st = 0;st < (1 << cnt);++st){
tmpAns = 0;
for(j = i;j < n;++j) tmpAns += (ANS[j] = ((st >> (n - j - 1)) & 1));
for(j = i - 1;j >= 0;--j){
int tmp = 0;
for(p = j + 1;p < n;++p) tmp = (tmp + A[j][p] * ANS[p]) % 2;
ANS[j] = ( (A[j][n] - tmp) % 2 + 2 ) % 2;
tmpAns += ANS[j];
}
minAns = min(tmpAns,minAns);
}
return minAns;
}
char tmpc;
int main(){
int T;sf("%d",&T);
while(T--){
sf("%d",&n);
init();getchar();
for(int i = 0;i < n * n;++i){
while((tmpc = getchar()) == '\n');
if(tmpc == 'y') A[i][n * n] = 0;
else A[i][n * n] = 1;
}
int ans = Gauss(A,n * n);
if(ans == INF) pf("inf\n");
else pf("%d\n",ans);
}
}