UVA - 11464 Even Parity

题意:改变矩阵中的0变为1,使得矩阵上每个数的周围的和是偶数,求最小的改变个数

,搜索的题目,先确定第一行的状态然后就是一行行的推了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 30;
const int INF = 0x3f3f3f3f;

int n;
int map[MAXN][MAXN];
int d[MAXN][MAXN];

int check(int s){
    memset(d,0,sizeof(d));
    for (int i = 1; i <= n; i++)
        if (s & (1<<(i-1)))
            d[1][i] = 1;
        else if (map[1][i])
            return INF;
    for (int i = 2; i <= n; i++)
        for (int j = 1; j <= n; j++){
            int sum = d[i-1][j-1] + d[i-2][j] + d[i-1][j+1];
            d[i][j] = sum % 2;
            if (!d[i][j] && map[i][j])
                return INF;
        }
    int cnt = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (d[i][j] != map[i][j])
                cnt++;
    return cnt;
}

int main(){
    int t;
    scanf("%d",&t);
    for (int cas = 1; cas <= t; cas++){
        memset(map,0,sizeof(map));
        scanf("%d",&n);
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                scanf("%d",&map[i][j]);
        int ans = INF;
        for (int s = 0; s < (1<<n); s++)
            ans = min(ans,check(s));
        if (ans != INF)
            printf("Case %d: %d\n",cas,ans);
        else printf("Case %d: -1\n",cas);
    }
    return 0;
}



你可能感兴趣的:(UVA - 11464 Even Parity)