洛谷P3812 【模板】线性基

题目背景

这是一道模板题。

题目描述

给定n个整数(数字可能重复),求在这些数中选取任意个,使得他们的异或和最大。

输入输出格式

输入格式:

第一行一个数n,表示元素个数

接下来一行n个数

输出格式:

仅一行,表示答案。

输入输出样例

输入样例#1:  复制
2
1 1
输出样例#1:  复制
1

说明

1 \leq n \leq 50, 0 \leq S_i \leq 2 ^ {50}1n50,0Si250

 

首先对这$n$个数建出线性基

然后贪心的选最大就好

线性基。。感觉又开了个天坑

#include<cstdio>
#include<cstring>
#include<algorithm>
#define int long long 
using namespace std;
const int MAXN = 2 * 1e6 + 10, INF = 1e9 + 10, B = 63;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N;
int P[MAXN];
void Insert(int x) {
    for(int i = B; i >= 0; i--) {
        if(x & (1ll << i)) {
            if(!P[i]) {P[i] = x; break;}
            x ^= P[i];
        }
    }
}
int Query() {
    int ans = 0;
    for(int i = B; i >= 0; i--) 
        if(ans < (ans ^ P[i]))
            ans = ans ^ P[i];
    return ans;
}
main() { 
#ifdef WIN32
    freopen("a.in", "r", stdin);
#endif
    N = read();
    for(int i = 1; i <= N; i++) {
        int val = read(); Insert(val);
    }
    printf("%lld", Query());
}

猜你喜欢

转载自www.cnblogs.com/zwfymqz/p/9190175.html
今日推荐