Link:
Http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & page = show_problem & problem = 2459
Ideas:
This is because the question is not well understood. I thought it was necessary to make the sum of the nine numbers around each grid an even number... It took me a long time to think about it. Later I found that it was just up, down, left, right...
In fact, it is brute force. enumerate the situations that can be changed in the first line, and then find the situations in the next line according to the first line. Note that 1 cannot be changed to 0.
#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int INF = 0x3f3f3f;const int maxn = 20;int n;int mat[maxn][maxn];int B[maxn][maxn];int check(int s){ memset(B, 0, sizeof(B)); for(int i=1; i<=n; ++i){ if(s & (1<<(i-1))) B[1][i]=1; else if(mat[1][i]) return INF; } for(int i=2; i<=n; ++i){ for(int j=1; j<=n; ++j){ int sum = B[i-2][j]+B[i-1][j-1]+B[i-1][j+1]; B[i][j] = sum&1; if(mat[i][j] && B[i][j]==0) return INF; } } int cnt=0; for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) if(mat[i][j] !=B[i][j]) ++cnt; return cnt;}int main(){ int T; scanf("%d", &T); memset(mat, 0, sizeof(mat)); for(int cas=1; cas<=T; ++cas){ scanf("%d", &n); for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) scanf("%d",&mat[i][j]); int ans = INF; for(int s=0; s<(1<<n); ++s) ans = min(ans, check(s)); if(ans == INF) ans=-1; printf("Case %d: %d\n", cas, ans); } return 0;}