uva 11464

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>

using namespace std;

#define MAXN (15+5)
#define INF 0x7f7f7f7f

int n, tot;
int fx[4][2] = {{-1,0}, {0,-1}, {1,0}, {0,1}};
int read[MAXN][MAXN], now_f[MAXN][MAXN];
int ans, ans_c, ans_f = INF;

bool diff(int a, int b){
	if(a != b) ans_c++;
	if(!a && b) return false;
	return true; 
}

void add(int a, int b){
	if(a < 0 || a > n || b < 0 || b > n) return;
	
	tot += now_f[a][b];
}

bool check(){
	tot = 0;
	
	for(int i = 1; i <= n; i++)
	  for(int j = 1; j <= n; j++){
	      int tot = 0;
	      for(int k = 0; k < 4; k++){
	          int x = i+fx[i][0], y = i+fx[i][1];
	          add(x, y);
		  }
		  if(tot%2) return false;
	  }
	
	return true;
}

void work(){
	ans_c = ans;
	
	for(int i = 2; i <= n; i++){
		int tmp = i>2? now_f[i-2][1]: 0;
		if((now_f[i-1][2]+tmp) % 2) now_f[i][1] = 1;
		else now_f[i][1] = 0;
		if(!diff(now_f[i][1], read[i][1])) return;
		
		tmp = i>2? now_f[i-2][n]: 0;
		if((now_f[i-1][n-1]+tmp) % 2) now_f[i][n] = 1;
		else now_f[i][n] = 0;
		if(!diff(now_f[i][n], read[i][n])) return;		
		
		for(int j = 2; j < n; j++){
			tmp = now_f[i-1][j-1] + now_f[i-1][j+1];
			tmp += i>2? now_f[i-2][j]: 0;

			if(tmp%2) now_f[i][j] = 1;
			else now_f[i][j] = 0;
			if(!diff(now_f[i][j], read[i][j])) return;
		}
	}
	
	if(check()) ans_f = min(ans_f, ans_c);
}

void dfs(int now){
	if(now > n){
		work();
		return;
	}
	
	bool ok = false;
	
	now_f[1][now] = 0;
	if(!read[1][now]) dfs(now+1);
	
	now_f[1][now] = 1;
	if(!read[1][now]) ans++, ok = true;
	dfs(now+1);
	if(ok) ans--, ok = false;
}

int main(){
	int T;
	scanf("%d", &T);
	
	int t = 0;
	while(T--){ 
		scanf("%d", &n);
		for(int i = 1; i <= n; i++)
		  for(int j = 1; j <= n; j++) scanf("%d", &read[i][j]);
		
		ans = 0; ans_f = INF;
		dfs(1);
		
		if(ans_f != INF) printf("Case %d: %d\n", ++t, ans_f); 
		else printf("Case %d: -1\n", ++t);
	}
	
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值