UVa 11464 Even Parity 题解

7 篇文章 0 订阅
4 篇文章 0 订阅
这是一道白书17页的题目。

题目大意:输入一个n*n的01矩阵(1<n<=15)
要求:将0置1,使每个项的前后左右之和为偶数,求最小翻动数。
暴力求解肯定不行,2^225≈5.8e76(tle)

所以想到局部枚举,下面的各行都可以依据上一行推导出。
下面给出推导下一行的例子:(3*3)

假设枚举第一行是这样,开始全为零(在下面代码中用二进制即(010)2=(2)10表示

1 0 1
0 0 0
0 0 0

从[0][0]开始:自己是1,右边是0,所以下面置1

1 0 1
1 0 0
0 0 0

[0][1]:自己是0,左边是1,右边是1,所以下面置0

1 0 1
1 0 0
0 0 0

[0][2]:自己是1,左边是0,所以下面是1

1 0 1
1 0 1
0 0 0

以此类推:
1 0 1
1 0 1
0 0 0

最后将得到的矩阵与输入的矩阵对比,不相同的为filp了的,计数
下面贴出ac代码
//#define DEBUG

#include<iostream>
#include<cstring>
#include<algorithm>

#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long
#define maxn 16
#define INF maxn*maxn+10
using namespace std;

int a[maxn][maxn], b[maxn][maxn];
int line;

int solve(int s) {
	memset(b, 0, sizeof(b));//第一行
	for (int c = 0; c < line; c++)
		if (s & (1 << c))//取flip位置
			b[0][c] = 1;
		else
			if (a[0][c] == 1)
				return INF;
	for(int r=1;r<line;r++)
		rep(c, line) {//b[r-1][c]
		int sum = 0;
		if (r > 1) sum += b[r - 2][c];
		if (c > 0) sum += b[r - 1][c - 1];
		if (c < line - 1) sum += b[r - 1][c + 1];
		b[r][c] = sum % 2;
		if (a[r][c] == 1 && b[r][c] == 0)
			return INF;//不能将1 flip为0
		}

	int cnt = 0;
	rep(i, line) rep(j, line)if (a[i][j] != b[i][j]) cnt++;//计算变化了多少个
	return cnt;
}

int main() {
	ios::sync_with_stdio(false);
	int count;
	cin >> count;
	rep(i, count) {
		cin >> line;
		rep(j, line) {
			rep(k, line) {
				cin>>a[j][k];
			}
		}
		int sum = INF;
		for (int i = 0; i < (1<< line); i++) {//第0行暴力flip,参数:第0行为1的位置
			sum = min(sum,solve(i));
		}
		if (sum == INF)
			sum = -1;
		cout << "Case " << i + 1 << ": " <<sum<< '\n';
	}
#ifdef DEBUG
	system("pause");
#endif // 


	return 0;
}
那个二进制想法挺牛的。最后要注意Case n: 后面的空格,我才不会说因为这个我这个蒟蒻pe了一次。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值