对所有可能进行枚举,不过情况太多了,只需枚举第一行的情况,剩下来的就可以确定了。
代码如下:
View Code
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 20; 7 const int INF = 1000000000; 8 int n, a[maxn][maxn], b[maxn][maxn]; 9 10 int check(int s) 11 { 12 memset(b, 0, sizeof(b)); 13 for(int i = 0; i < n; i++) 14 { 15 if(s & (1<<i)) b[0][i] = 1; 16 else if(a[0][i] == 1) return INF; 17 } 18 for(int i = 1; i < n; i++) 19 for(int j = 0; j < n; j++) 20 { 21 int sum = 0; 22 if(i > 1) sum += b[i-2][j]; 23 if(j > 0) sum += b[i-1][j-1]; 24 if(j < n-1) sum += b[i-1][j+1]; 25 b[i][j] = sum % 2; 26 if(a[i][j] == 1 && b[i][j] == 0) return INF; 27 } 28 int cnt = 0; 29 for(int i = 0; i < n; i++) 30 for(int j = 0; j < n; j++) 31 if(a[i][j] != b[i][j]) cnt++; 32 return cnt; 33 } 34 35 int main() 36 { 37 #ifdef LOCAL 38 freopen("in", "r", stdin); 39 #endif 40 int T; 41 scanf("%d", &T); 42 for(int kase = 1; kase <= T; kase++) 43 { 44 scanf("%d", &n); 45 for(int i = 0; i < n; i++) 46 for(int j = 0; j < n; j++) 47 scanf("%d", &a[i][j]); 48 int ans = INF; 49 for(int i = 0; i < (1<<n); i++) 50 ans = min(ans, check(i)); 51 if(ans == INF) ans = -1; 52 printf("Case %d: %d\n", kase, ans); 53 } 54 return 0; 55 }