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.
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.
我的代码使用了类似于背包算法的方法对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;
}