版权声明:如需转载,记得标识出处 https://blog.csdn.net/godleaf/article/details/82118528
题目链接:https://cn.vjudge.net/problem/UVA-11464
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
int read(){
int r=0,f=1;char p=getchar();
while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}
while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}
typedef long long ll;
typedef unsigned long long ull;
const int Maxn = 20;
const long long LINF = 1e18;
const int INF = 0x3f3f3f3f;
const int Mod = 10001;
int a[Maxn][Maxn],b[Maxn][Maxn];
int solve (int n, int h) {
memcpy(b,a,sizeof(b)); // 把a的值复制到b中,重复使用a
int cnt = 0;
for (int i = n; i > 0; --i) { // 把第一行的值用位运算赋值到b的第一行中
b[1][i] = (h>>(n-i))&1;
if(!b[1][i] && a[1][i]) return INF; // 如果发现 赋值后的值为0,原始值为1,直接返回INF,
if(b[1][i] && !a[1][i]) cnt++; //因为1不能转换为0
}
int tmp; // 递推: 第一行确定为固定值,用第一行的值给第二行赋值 比如根据 b[1][2]+b[2][1]
for (int i = 2; i <= n; ++i) { // 来判断b[2][1]应该赋什么值,固定第一行,改变第二行的值
for (int j = 1; j <= n; ++j) {
tmp = b[i-1][j+1]+b[i-1][j-1]+b[i-2][j]+b[i][j];
if(tmp%2 != 0) { //因为我是从1开始的,所以b[0]和b[n+1]的值都是0,不怕越界
if(!b[i][j]) {
b[i][j] = 1;
cnt++;
} else return INF;
}
}
}
for (int i = 1; i <= n; ++i) { // 因为最后一行是根据n-1赋值的(n-1就可能满足条件),
tmp = b[n][i-1]+b[n][i+1]+b[n-1][i]; //所以还要而外加多判断最后一行是否满足条件
if(tmp%2 != 0) return INF;
}
return cnt;
}
int main (void)
{
int t,n;
scanf("%d",&t);
for (int cas = 1; cas <= t; ++cas) {
scanf("%d",&n);
memset(a,0,sizeof(a)); // 注意初始化;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
scanf("%d",&a[i][j]);
}
}
int ans = INF;
for (int i = 0; i < 1<<n; ++i) { // 枚举第一行的情况
ans = min(ans,solve(n,i));
}
if(ans == INF) ans = -1;
printf("Case %d: %d\n",cas,ans);
}
return 0;
}