P3812 【模板】线性基
题目描述
给定n个整数(数字可能重复),求在这些数中选取任意个,使得他们的异或和最大
题解:
把所有数insert进入线性基,把线性基中所有元素xor起来 = ans
代码:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
inline int read(){int s=0,w=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();//s=(s<<3)+(s<<1)+(ch^48);return s*w;
}
const int maxn=60;
ll a[maxn],c[maxn];
int L=60;
bool insert(ll x){for(int j=L;j>=0;--j){//从最高位开始看if((x&(1ll<<j))==0) continue;if(a[j]){//若如主元j已经存在,用a[j]消去x的第j位然后继续x ^= a[j];continue;} //让x当主元j,需要先用第k(k<j)个主元消去x的第k位for(int k=j-1;k>=0;k--){if(x & (1ll<<k)) x ^= a[k];}//接着用x去消掉第k(k>j)个主元的第j位for(int k=L;k>j;k--){if(a[k] & (1ll<<j)) a[k] ^= x;}a[j] = x;return 1; }return 0;
}
int main()
{int n;cin>>n;for(int i=1;i<=n;i++){ll x;cin>>x;insert(x);}ll w=0;for(int i=L;i>=0;i--){w^=a[i];}cout<<w;
}