Even Parity UVA - 11464
题意:
有一个01矩阵。现要求你变换,使得一个格子的上下左右的和为偶数。
操作:
把最少的0变为1。
思路:
- 就是熄灯问题,可以通过枚举第一行,来确定剩下的ans。
- 对于 与题意冲突的枚举,可以直接跳过。
AC
#include <iostream>
#include <bits/stdc++.h>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
#define rep(i,y,x) for(int i=(y); i>=(x); i--)
#define mst(x,a) memset(x,a,sizeof(x))
#define pb push_back
#define sz(a) (int)a.size()
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int,int>pa;
typedef pair<ll,ll>pai;
const int INF = 0x3f3f3f3f;
int g[30][30], b[30][30];
int n;
int check(int s){
mst(b, 0);
fori(i, 0, n){
if((s>>i)&1)b[0][i] = 1;
else if(g[0][i])return INF;
}
fori(i,1,n){
fori(j,0,n){
int res = 0;
if(j-1>=0)res += b[i-1][j-1];
if(j+1<n)res += b[i-1][j+1];
if(i-2>=0)res += b[i-2][j];
b[i][j] = res%2;
if(g[i][j]&&res%2==0)return INF;
}
}
int cnt = 0;
// cout<<"s-------"<<s<<endl;
// fori(i,0,n){
// fori(j,0,n)cout<<b[i][j]<<' ';
// cout<<endl;
// }
fori(i,0,n)fori(j,0,n)if(b[i][j]!=g[i][j])cnt++;
return cnt;
}
int main()
{
//ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int tt, kase = 0; scanf("%d", &tt);
while(tt--){
scanf("%d", &n);
fori(i,0,n)fori(j,0,n)scanf("%d", &g[i][j]);
int ans = INF;
// cout<<(int)(1<<n)<<endl;
fori(i,0,(int)(1<<n))ans = min(ans,check(i));
printf("Case %d: %d\n", ++kase, (ans==INF?-1:ans));
}
return 0;
}