Even Parity
We have a grid of size N x 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 x 4:
1 | 0 | 1 | 0 | The parity of each cell would be | 1 | 3 | 1 | 2 |
1 | 1 | 1 | 1 | 2 | 3 | 3 | 1 | |
0 | 1 | 0 | 0 | 2 | 1 | 2 | 1 | |
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
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 Output for 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 | Case 1: 0 |
题意:给你一个n*n的0 1 矩阵(每个元素非0即1),你的任务是把尽量少的0变成1,使得每个元素的上下左右的元素(如果存在)之和均为偶数。比如把0 0 0 变成 0 1 0
1 0 0 1 0 1
0 0 0 0 1 0
至少要把3个0变成1,最终才能得到正确结果,如上所示。
思路:也许最容易想到的方法就是枚举每个数字“变”还是“不变”,最后判断整个矩阵是否满足条件。遗憾的是,这样做最多需要枚举2^255 =5*10^67种情况,实在难以承受。
注意到n只有15,第一行只有不超过2^15=32768种情况,所以第一行的情况是可以枚举的。接下来根据第一行可以完全计算出第二行,根据第二行又能计算出第三行(想一想,如何计算),如此类推,这样,总的时间复杂度即可降为O(2^ * n^2)。
代码如下:
#include <stdio.h>
#include <string.h>
#define INF 100000000
int n,A[20][20],B[20][20];
int min(int a,int b)
{
return a < b ? a : b;
}
int check(int s)
{
int i,j,k,sum=0,num;
memset(B,0,sizeof(B));
for(i=1;i<=n;i++)
{
if(s & 1<<(i-1))//判断枚举的情况中1的位置
B[1][i]=1;
else if(A[1][i]==1)//1不能变成0
return INF;
}
for(i=2;i<=n;i++)
{
for(j=1;j<=n;j++)
{
sum = 0;
sum+=B[i-1][j-1]+B[i-1][j+1]+B[i-2][j];//上下左右四个元素之和
B[i][j]=sum%2;
if(A[i][j]==1 && B[i][j]==0)//1不能变成0
return INF;
}
}
num = 0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(A[i][j]!=B[i][j])
num++;
return num;
}
int main()
{
int kk,T;
scanf("%d",&T);
for(kk=1;kk<=T;kk++)
{
int i,j,k,ans;
memset(A,0,sizeof(A));
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&A[i][j]);
ans = INF;
for(k=0;k<(1<<n);k++)
{
ans=min(ans,check(k));
}
if(ans == INF)
ans = -1;
printf("Case %d: %d\n",kk,ans);
}
return 0;
}
体会:代码中的if(s & 1<<(i-1)) 这一句,刚开始看了很久也没想明白,最后问了一下亚龙,明白了什么意思,判断枚举的那个状态0 的位置。举个例子具体说一下,例如枚举到 0 1 0 这种情况,当i=1时, s&(i-1) = 0,即这种状态最后一位为0,i=2时, s&(i-1) = 1,即这种状态最后一位为1,所以把B数组的这一位赋值为1.
位运算很强大
标签:枚举、状态压缩