HDU 3364 (高斯消元)

求出每种状态下的自由元个数n,答案就是2^n.

#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
#define maxn 333
#define free Free

int a[maxn][maxn];
int aa[maxn][maxn];
int n, m;
int free[maxn*maxn]; //标记自由元
int x[maxn*maxn], cnt; //解集 自由元个数
int equ, var; //方程个数 未知数个数

int Gauss () {
    int max_r, col, k; //最大的数在的行 当前处理的列
    cnt = 0; //自由元个数
    for (k = 0, col = 0; k < equ && col < var; k++, col++) {
        max_r = k;
        for (int i = k+1; i < equ; i++) { //找到最大的数所在的行
            if (abs (a[i][col]) > abs (a[max_r][col]))
                max_r = i;
        }
        if (max_r != k) { //交换最大的数所在的行和当前行
            for (int i = 0; i <= var; i++)
                swap (a[k][i], a[max_r][i]);
        }
        if (a[k][col] == 0) { //判断自由元 处理当前行的下一列
            k--;
            free[cnt++] = col;
            continue;
        }
        for (int i = k+1; i < equ; i++) {
            if (a[i][col]) {
                for (int j = col; j <= var; j++) {
                    a[i][j] ^= a[k][j];
                }
            }
        }
    }

    for (int i = k; i < equ; i++) { //判断无解情况
        if (a[i][col])
            return -1;
    }
    if (k < var)
        return var - k; //返回自由元个数

    for (int i = var-1; i >= 0; i--) { //回代
        x[i] = a[i][var];
        for (int j = i+1; j < var; j++)
            x[i] ^= (a[i][j] && x[j]);
    }
    return 0;
}
int main () {
    //freopen ("in", "r", stdin);
    int t, kase = 0;
    scanf ("%d", &t);
    while (t--) {
        printf ("Case %d:\n", ++kase);
        scanf ("%d%d", &n, &m);
        memset (aa, 0, sizeof aa);
        for (int i = 0; i < m; i++) {
            int x;
            scanf ("%d", &x);
            for (int j = 0; j < x; j++) {
                int id;
                scanf ("%d", &id); id--;
                aa[id][i] = 1;
            }
        }

        equ = n, var = m;
        int q;
        scanf ("%d", &q);
        while (q--) {
            memset (a, 0, sizeof a);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++)
                    a[i][j] = aa[i][j];
            }
            for (int i = 0; i < n; i++) {
                int x;
                scanf ("%d", &x);
                a[i][var] = x;
            }
            int ans = Gauss ();
            if (ans == -1) {
                printf ("0\n");
            }
            else printf ("%lld\n", (long long)pow (2, ans));
        }
    }
    return 0;
}


你可能感兴趣的:(HDU 3364 (高斯消元))