POJ-1681 Painter's Problem 高消

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define TO(x, y) (x-1)*N+y
using namespace std;

char G[30][30];

int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}, N;

int C;

inline bool judge(int x, int y)
{
    if (x < 1 || x > N || y < 1 || y > N) {
        return false;
    }   
    return true;
}

void swap(int &a, int &b) 
{
    int t = a;
    a = b;
    b = t;
}

struct Matrix
{
    int a[300][300];
    void init() {
        int xx, yy, k, pos;
        memset(a, 0, sizeof (a));
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                k = TO(i, j);
                a[k][k] = 1;
                for (int d = 0; d < 4; ++d) {
                    xx = i + dir[d][0], yy = j + dir[d][1];
                    if (judge(xx, yy)) {
                        pos = TO(xx, yy);
                        a[pos][k] = 1;
                    }
                }
            }
        }
    }
    void rswap(int x, int y, int s) {
        for (int j = s; j <= C+1; ++j) {
            swap(a[x][j], a[y][j]);
        }
    }
    void relax(int x, int y, int s) {
        for (int j = s; j <= C+1; ++j) {
            a[y][j] ^= a[x][j];
        }
    }
}M;

void solve(int R)
{ 
    int f1 = 0,  x1[300], t1, ans1 = 0x3fffffff;
    for (int i = R + 1; i <= C; ++i) {
        if (M.a[i][C+1]) f1 = 1;
    }
    if (f1) {
        puts("inf");
        return;
    }
    for (int s = 0; s < 1<<(C-R); ++s) {
        t1 = 0;
        memset(x1, 0, sizeof (x1)); 
        for (int i = 0; i < (C-R); ++i) {
            x1[R+i+1] = s & (1 << i) ? 1 : 0;
            if (x1[R+i+1]) ++t1;
        }
        for (int i = R; i >= 1; --i) {
            for (int j = i + 1; j <= C; ++j) {
                 x1[i] ^= (x1[j] * M.a[i][j]); 
            }
            x1[i] ^= M.a[i][C+1];
            if (x1[i]) ++t1;
        }
        ans1 = min(ans1, t1);
    }
    printf("%d\n", ans1);
}

void Gauss()
{
    int i = 1, k;
    for (int j = 1; j <= C; ++j) { // 枚举上三角矩阵的对角线
        for (k = i; k <= C; ++k) {
            if (M.a[k][j])  break;
        }
        if (k > C) continue;
        if (k != i) {  // 如果该行就是第首行,那么我们直接进行消元,否则交换行,使得第一行为单位1
            M.rswap(k, i, j);
        }
        for (k = i + 1; k <= C; ++k) {  // 从下一行开始进行消元
            if (M.a[k][j]) {
                M.relax(i, k, j);
            }
        }
        ++i;
    } 
    solve(i - 1);
}

int main()
{
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d", &N);
        C = N*N;
        M.init();
        for (int i = 1; i <= N; ++i) {
            scanf("%s", G[i] + 1);
        }
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                M.a[TO(i, j)][C+1] = G[i][j] == 'w';
            }
        }
        Gauss();
    }
    return 0;
}
posted @ 2012-07-26 22:56  沐阳  阅读(304)  评论(0编辑  收藏  举报