Codeforces 961C Chessboard (Educational Codeforces Round 41) (暴力枚举)

C. Chessboard
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white.

Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.

Input

The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board.

Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.

Output

Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
Examples
Input
Copy
1
0

0

1

0
Output
Copy
1
Input
Copy
3
101
010
101

101
000
101

010
101
011

010
101
010
Output
Copy
2


对给定的棋盘碎片进行最少步数染色以拼接成整块棋盘。

显然,最终结果的四个棋盘中有两个左上角元素为0,两个左上角元素为1。
对四个矩阵左上角的值进行枚举,共有4*3=12种,而原矩阵仅为100*100,对于任意位置,通过chessboard[k][i][j]-'0'==(((i+j)%2)^bag[k])判断是否需要染色暴力枚举时间足够

我的代码使用了类似于背包算法的方法对bag进行修改,进行直接循环或进制穷举的方法同样是可以的。


#include<bits/stdc++.h>
using namespace std;

const int MAXN=110;
char chessboard[5][MAXN][MAXN];

int main(){
	int n;
	char ch;
	scanf("%d",&n);
	for (int num=1;num<=4;num++){
		for (int k=1;k<=n;k++){
			cin>>chessboard[num][k];
		}
	}
	int bag[5]={0,0,0,1,1};
	int ans=99999999;
	while (!bag[0]){
		int temp=0;
		for (int k=1;k<=4;k++){
			for (int i=1;i<=n;i++){
				for (int j=0;j<n;j++){
					if (chessboard[k][i][j]-'0'==(((i+j)%2)^bag[k])){
						temp++;
					}
				}
			}
		}
		if (ans>temp)
			ans=temp;
		int k=4;
		while (!bag[k]){
			k--;
		}
		if (!bag[k-1]){
			bag[k]=0;
			bag[k-1]=1;
		}
		else{
			bag[k-1]=0;
			bag[k]=0;
			bag[k-2]=1;
			bag[4]=1;
		}
	}
	cout<<ans<<endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值