uva11464 Even Parity

本文探讨了一个N×N的01矩阵问题,目标是最少地将0转换为1,确保每个元素的上下左右之和为偶数。通过枚举第一行所有可能状态并推导后续行的方法,实现了高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给一个nXn的01矩阵,你的任务是把尽量少的0变成1,使得每个元素的上下左右之和均为偶数

思路:显然枚举每一位是不现实的,注意到n只有15,第一行只有不超过2^15种可能,那么可以枚举第一行,接下来根据第一行就可以计算出第二行,根据第二行又能计算出第三行,这样复杂度就可以降为2^n*n^2


#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 20
#define LL long long
#define INF 1e9
int cas=1,T;
int A[maxn][maxn],B[maxn][maxn],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;
			if (r>1)
				sum+=B[r-2][c];
			if (c>=1)
				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] && !B[r][c])
				return INF;
		}
	int cnt = 0;
	for (int r=0;r<n;r++)
		for (int c = 0;c<n;c++)
			if (A[r][c]!=B[r][c])
				cnt++;
	return cnt;
}
int main()
{
	//freopen("in","r",stdin);
	scanf("%d",&T);
	while (T--)
	{
		printf("Case %d: ",cas++);
		scanf("%d",&n);
		for (int i = 0;i<n;i++)
			for (int j = 0;j<n;j++)
				scanf("%d",&A[i][j]);
        
		int ans = INF;
		for (int i = 0;i<(1<<n);i++)
		{
            ans = min(ans,check(i));
		}
        if (ans == INF)
			ans=-1;
	    printf("%d\n",ans);
	}
	//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
	return 0;
}



We have a grid of size N × N. Each cell of the grid initially contains a zero(0) or a one(1). The parityof 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:1 0 1 0 The parity of each cell would be 1 3 1 21 1 1 1 2 3 2 10 1 0 0 2 1 2 10 0 0 0 0 1 0 0For this problem, you have to change some of the 0s to 1s so that the parity of every cell becomeseven. We are interested in the minimum number of transformations of 0 to 1 that is needed to achievethe desired requirement.

Input

The first line of input is an integer T (T < 30) that indicates the number of test cases. Each case startswith a positive integer N (1 ≤ N ≤ 15). Each of the next N lines contain N integers (0/1) each. Theintegers 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值