POJ1681 Painter's Problem 题解 高斯消元法解异或方程组

题目链接:http://poj.org/problem?id=1681

题目大意:略

解题思路:略(因为是模板题)

示例程序:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 255;

int T, N, n, a[maxn][maxn];
char s[22][22];

int id(int x, int y) {
    return x * N + y + 1;
}

bool gauss() {
    for (int i = 1; i <= n; i++) {
        int r = i;
        for (int j = i; j <= n; j++) {
            if (a[j][i]) {
                r = j;
                break;
            }
        }
        if (!a[r][i]) {
            if (a[r][n+1]) return false;
            else continue;
        }
        for (int j = i; j <= n+1; j++)
            swap(a[i][j], a[r][j]);
        for (int j = 1; j <= n; j++) {
            if (j != i && a[j][i]) {
                for (int k = 1; k <= n+1; k++)
                    a[j][k] ^= a[i][k];
            }
        }
    }
    return true;
}

int main() {
    scanf("%d", &T);
    while (T--) {
        scanf("%d", &N);
        for (int i = 0; i < N; i++)
            scanf("%s", s[i]);
        n = N * N;
        memset(a, 0, sizeof a);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                a[id(i, j)][n+1] = (s[i][j] == 'w');
                a[id(i, j)][id(i, j)] = 1;
                if (j+1 < N) a[id(i, j+1)][id(i, j)] = 1;
                if (i+1 < N) a[id(i+1, j)][id(i, j)] = 1;
                if (j) a[id(i, j-1)][id(i, j)] = 1;
                if (i) a[id(i-1, j)][id(i, j)] = 1;
            }
        }
        if (!gauss()) puts("inf");
        else {
            int res = 0;
            for (int i = 1; i <= n; i++)
                res += a[i][n+1];
            printf("%d\n", res);
        }
    }
    return 0;
}
posted @ 2024-12-15 17:25  quanjun  阅读(22)  评论(0)    收藏  举报