Even Parity
We have a grid of size N × N. Each cell of the grid initially contains a zero(0) or a one(1). The parity of a cell is the number of 1s surrounding that cell. A cell is surrounded by at most 4 cells (top, bottom, left, right).
Suppose we have a grid of size 4 × 4:
For this problem, you have to change some of the 0s to 1s so that the parity of every cell becomes even. We are interested in the minimum number of transformations of 0 to 1 that is needed to achieve the desired requirement.
Input
The first line of input is an integer T (T < 30) that indicates the number of test cases. Each case starts with a positive integer N (1 ≤ N ≤ 15). Each of the next N lines contain N integers (0/1) each. The integers are separated by a single space character.
Output
For each case, output the case number followed by the minimum number of transformations required. If it’s impossible to achieve the desired result, then output ‘-1’ instead.
Sample Input
3
3
0 0 0
0 0 0
0 0 0
3
0 0 0
1 0 0
0 0 0
3
1 1 1
1 1 1
0 0 0
Sample Output
Case 1: 0
Case 2: 3
Case 3: -1
此题采用部分枚举的手段,通过枚举第一行(对于每一个测试数据最坏仅仅需要枚举2^15种情况),将余下n-1行对应的确切结果推导出来,减少无谓的枚举,将时间复杂度从暴力枚举的O(2^(15*15))减低到了部分枚举的O((2^15)*(n^2))。
附代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INF 100000+5
#define MAXN 15+5
int A[MAXN][MAXN],B[MAXN][MAXN];
int n;
int check(int s){
memset(B,0,sizeof(B));
for(int c=0;c<n;c++){
if(s & (1<<c)) B[0][c]=1;
else if(A[0][c]==1) return INF;
}
for(int r=1;r<n;r++){
for(int c=0;c<n;c++){
int sum=0;//计算A[r-1][c]的Parity值
if(r>1)sum+=B[r-2][c];
if(c>0)sum+=B[r-1][c-1];
if(c<n-1)sum+=B[r-1][c+1];
B[r][c]=sum%2;
if(A[r][c]==1&&B[r][c]==0) return INF;
}
}
int num=0;
for(int r=0;r<n;r++){
for(int c=0;c<n;c++){
if(A[r][c]!=B[r][c])num++;
}
}
return num;
}
int main(){
int total;
scanf("%d",&total);
for(int k=1;k<=total;k++){
scanf("%d",&n);
for(int r=0;r<n;r++)
for(int c=0;c<n;c++) scanf("%d",&A[r][c]);
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",k,ans);
}
return 0;
}