【模板】线性基

线性基主要用于解决子集异或问题。

#include 

using namespace std;

typedef long long LL;

struct linear_basis {
    vector s;
    int n, zero;
    linear_basis(int _n) {
        n = _n;
        s.resize(n + 1);
        zero = 0;
    }
    void insert(LL x) {
        for (int i = n; i >= 0; i--) {
            if (x >> i & 1) {
                if (s[i] != 0) {
                    x ^= s[i];
                } else {
                    s[i] = x;
                    return;
                }
            }
        }
        zero = 1;
    }
    LL query_max() {
        LL ret = 0;
        for (int i = n; i >= 0; i--) {
            if (ret < (ret ^ s[i])) {
                ret ^= s[i];
            }
        }
        return ret;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    int n;
    cin >> n;
    linear_basis s(51);
    for (int i = 0; i < n; i++) {
        LL x;
        cin >> x;
        s.insert(x);
    }
    cout << s.query_max() << endl;
    return 0;
} 

转载于:https://www.cnblogs.com/wzj-xhjbk/p/11600196.html

你可能感兴趣的:(【模板】线性基)