uva - 11464 - Even Parity(部分枚举,递推)

题意:给你一个nxn的矩阵01矩阵,(每个元素非0就1),你的任务是把尽量少的0变成1,使矩阵的每个元素的上下左右的元素只和均为偶数。

方法:枚举每个数字变或者不变有2^255太大。但是枚举第一行只有2^15,然后根据第一行计算下边的就行。注意是从上到下,从左到右计算,也就是得到的肯定是满足题意的。如果出现矛盾,则这种枚举不合适,返回INF。

#include <iostream>  
#include <iomanip>  
#include <string>  
#include <cstring>  
#include <cstdio>  
#include <queue>  
#include <stack>  
#include <algorithm>  
#include <cmath>  
#include <ctime>

using namespace std;

const int maxn = 20;
const int INF = 100000000;
int n, A[maxn][maxn], B[maxn][maxn];

int check(int s)
{
	int c = 0, r = 0;
	memset(B, 0, sizeof(B));
	for (c = 0; c < n; c++)
	{
		if (s & (1 << c))
			B[0][c] = 1;
		else if (A[0][c] == 1)
			return INF;
	}
	for (r = 1; r < n; r++)
	{
		for (c = 0; c < n; c++)
		{
			int sum = 0;
			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 cnt = 0;
	for (r = 0; r < n; r++)
		for (c = 0; c < n; c++)
			if (A[r][c] != B[r][c])
				cnt++;
	return cnt;
}

int main() 
{
#ifdef Local    
	freopen("a.in", "r", stdin);    
#endif
	int t = 0, i = 0, j = 0, c = 0, r = 0;
	cin >> t;
	for (i = 1; i <= t; i++)
	{
		cin >> n;
		for (r = 0; r < n; r++)
			for (c = 0; c < n; c++)
				cin >> A[r][c];
		int ans = INF;
		for (j = 0; j < (1 << n); j++)
			ans = min(ans, check(j));
		if (ans == INF)
			ans = -1;
		cout << "Case "<< i << ": " << ans << endl;
	}
}

1、不知道是vs还是格式的问题,括号该打上就打上,别看着格式对就不打了,调试的时候因为check中一个循环没打,造成下一个循环c不变,一直是3。

2、注意理解

if (A[r][c] == 1 && B[r][c] == 0) return INF;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值