UVa 11464 EvenParity 偶数矩阵

来源:互联网 发布:php生成二维码代码 编辑:程序博客网 时间:2024/06/06 02:41

题意:给定一个n*n的01矩阵(每个元素非0即1),要求把尽量少的0变成1,使得每个元素的上下左右的元素(如果存在)之和均为偶数。





暴力水题。当然也不能太暴力啦。很容易的一种想法是枚举每个0的位置是否需要变化,这样的复杂度将是O(2^(n^2))的复杂度是会TLE的。但是我们可以只枚举第一排的0。因为第一排的元素只受第一排和第二排元素的影响。所以第一排元素如果确定下来了,第二排的元素实际上是可以唯一确定的。而第二排的元素又只受第一排、第二排、第三排元素的影响,因此确定了第一排和第二排的元素后,第三排的元素也是确定的。以此类推,如果前n排元素确定了,那么第n + 1排元素就可以确定。所以我们可以只需要枚举第一排哪些0需要变为1,然后依次计算完每一排元素,最后判断一下最后一排元素是符合要求就可以了。用二进制方式映射10进制数枚举即可。在处理上,可以假设第一排的元素都是0,如果枚举到某种情况发现第一排某个元素为0而原来的矩阵上对应位置为1,直接判不符合条件即可。




#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <algorithm>#include <stack>#include <queue>#include <vector>#include <map>#include <set>using namespace std;const int MAX = 20;const int INF = 1000;int n;int a[MAX][MAX];int temp[MAX][MAX];int get(int i, int j) //判断当前元素的取值{    int value = 0;    if(i > 1)        value += temp[i - 2][j];    if(j > 0)        value += temp[i - 1][j - 1];    if(j < n - 1)        value += temp[i - 1][j + 1];    return value%2;}int cal(int x){    int res = 0;    for(int i = 0; i < n; i++) //计算第一排元素    {        temp[0][i] = x%2;        if(temp[0][i] == 0 && a[0][i] == 1) //如果把1变成了0不符合要求            return INF;        if(temp[0][i] == 1 && a[0][i] == 0)            res++;        x /= 2;    }    for(int i = 1; i < n; i++)    {        for(int j = 0; j < n; j++)        {            temp[i][j] = get(i, j);            if(temp[i][j] == 0 && a[i][j] == 1) //如果把1变成了0不符合要求                return INF;            if(temp[i][j] == 1 && a[i][j] == 0)                res++;        }    }    for(int i = 0; i < n; i++) //检验最后一排元素是否符合要求    {        int value = 0;        if(n > 1)            value += temp[n - 2][i];        if(i > 0)            value += temp[n - 1][i - 1];        if(i < n - 1)            value += temp[n - 1][i + 1];        if(value%2)            return INF;    }    return res;}void input(){    scanf("%d", &n);    for(int i = 0; i < n; i++)    {        for(int j = 0; j < n; j++)            scanf("%d", &a[i][j]);    }}void solve(){    int ans = INF, total = 1;    for(int i = 0; i < n; i++)        total *= 2;    while(total--)        ans = min(ans, cal(total));    if(ans == INF)        ans = -1;    printf("%d\n", ans);}int main(){    int T;    scanf("%d", &T);    for(int t = 1; t <= T; t++)    {        input();        printf("Case %d: ", t);        solve();    }    return 0;}

0 0
原创粉丝点击