Codeforces 961 C. Chessboard

题目链接:点击打开链接

题目大意:给四个n*n的正方形矩阵,里面的数只有0和1,可以把它们任意组合成一个2n*2n的正方形(只能平移,不能旋转、翻转),你要改变其中的数,让正方形中的任意元素上下左右的元素都不与其相同,输出最小的改变次数。

解题思路:用一个in数组保存输入的四个正方形,用一个cur数组保存大正方形,从所有情况中选出需要改变最少的就是ans。

注:可以用next_permutation来改变排列,这样就不需要依次枚举了。

代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#define FAST ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
typedef long long ll;
const int INF = 0x3f3f3f3f;
using namespace std;

char in[4][105][105];
char cur[205][205];

int u[4];

int main() {
	FAST;
	int n;
	scanf("%d", &n);
	for(int i = 0; i < 4; i++) 
		for(int j = 0; j < n; j++) 
			scanf("%s", in[i][j]);
	for(int i = 0; i < 4; i++) u[i] = i;
	int ans = INF;
	do{
		for(int i = 0; i < 4; i++){
			for(int j = 0; j < n; j++) 
				for(int k = 0; k < n; k++) 
					cur[(i / 2)*n + j][(i % 2)*n + k] = in[u[i]][j][k];//精华代码!
		}
		int cnt = 0;
		for(int i = 0; i < 2 * n; i++){
			for(int j = 0; j < 2 * n; j++){
				char c = '0' + (i + j) % 2;
				if (c != cur[i][j]) cnt++;
			}
		}
		ans = min(ans, cnt);
	}while(next_permutation(u, u + 4));
	return printf("%d\n", ans), 0;
}

猜你喜欢

转载自blog.csdn.net/swunhj/article/details/80009576