线性基小计
线性基小计
定义
就是在一个集合
构造方法
对于每个数,考虑如何插入,从高位到低位遍历,如果这位没有数,直接插入,否则异或上这位的数然后继续向下找,正确性显然
int insert(int x){
for(int i=31;i>=0;i--){
if((x>>i)&1){
if(!d[i]){
d[i]=x;
return 1;
}
else x^=d[i];
}
}
return 0;
}
例题
T1 [CQOI2013] 新Nim游戏
利用 NIM 游戏的经典结论,如果所有堆中石子的数量异或和不为 0,则先手必胜
目标转化为了找到一组和最大的任取一些数异或和不为 0 的使得
考虑从大到小插入线性基,如果能插入就插入,这样一定是最优的
:::info 关于为何要从大到小排序,感性理解下就是对于一个线性基里的位置,如果既可以被小数占据,又可以被大数占据,按照我们的选法一定会被大数占据,这一定是不劣的 :::
:::success[code]
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define PII pair<int,int>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define ivoid inline void
ivoid wsp(int x){
cout<<x<<" ";
}
ivoid wln(int x){
cout<<x<<"\n";
}
ivoid wstr(string s){
cout<<s<<"\n";
}
#define cout cerr
const int maxn=1e2+10;
int n,a[maxn];
struct LinearBase{
int d[maxn];
int insert(int x){
for(int i=31;i>=0;i--){
if((x>>i)&1){
if(!d[i]){
d[i]=x;
return 1;
}
else x^=d[i];
}
}
return 0;
}
}lb;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a+1,a+n+1,greater<int>());
int ans=0;
for(int i=1;i<=n;i++){
if(!lb.insert(a[i])) ans+=a[i];
}
wln(ans);
return 0;
}
:::