POJ 1830 开关问题 (01高斯消元)

题意

有n个开关,按动按钮可以改变灯泡的开关状态,有些开关之间是有联系的,给出初始状态和目标状态,求是否可行,如果可行,求方案数目。

思路

我们可以另矩阵 [x1,x2...xn] 来表示解集,即第i个开关需要按动的次数,最后的状态即 [b1,b2...bn] ,原状态是 [a1,a2...an] ,即A*X=B,这里没有要求解出 xi ,求出自由元的个数就可以了。

代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define Lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int maxn = 1e5 + 10;
const double eps = 1e-8;
const double PI = acos(-1.0);
typedef pair<int, int> pii;
int mat[35][35];
int x[35], a[35], b[35];
int var, equ;

int gauss()
{
    int k, col, max_r;
    for (k = 0, col = 0; k < equ && col < var; k++, col++)
    {
        max_r = k;
        for (int i = k + 1; i < equ; i++)
        {
            if (abs(mat[i][col]) > abs(mat[max_r][col]))
                max_r = i;
        }
        if (mat[max_r][col] == 0)
        {
            k--;
            continue;
        }
        if (max_r != k)
        {
            for (int j = col; j < var + 1; j++)
                swap(mat[k][j], mat[max_r][j]);
        }
        for (int i = k + 1; i < equ; i++)
        {
            if (mat[i][col] != 0)
            {
                for (int j = col; j < var + 1; j++)
                    mat[i][j] ^= mat[k][j];
            }
        }
    }
    for (int i = k; i < equ; i++)
        if (mat[i][col] != 0)
            return -1;
    if (k < var) return var - k;
    for (int i = var - 1; i >= 0; i--)
    {
        x[i] = mat[i][var];
        for (int j = i + 1; j < var; j++)
            x[i] ^= (mat[i][j] && x[j]);
    }
    return 0;
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int n;
        memset(mat, 0, sizeof(mat));
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        memset(x, 0, sizeof(x));
        scanf("%d", &n);
        var = equ = n;
        for (int i = 0; i < n; i++)
            scanf("%d", &a[i]);
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &b[i]);
            if (a[i] != b[i])
                mat[i][n] = 1;
            mat[i][i] = 1;
        }
        int i, j;
        while (scanf("%d%d", &i, &j))
        {
            if (!i && !j) break;
            mat[j-1][i-1] = 1;
        }
        int ans = gauss();
        if (ans == -1)
            puts("Oh,it's impossible~!!");
        else
            printf("%d\n", 1 << ans);
    }
    return 0;
}

你可能感兴趣的:(poj)