前言
考场上不知为何就想出了这个解法,如有细节错误,求神犇指点。
思路
这道题可以利用前缀和和字典树来求解。
首先我们知道两个性质,那就是 ,。
然后我们把数组分为左右两边,枚举两段区间之间的断点。
我们用 表示区间 所能得到的区间异或最大值,用 表示区间 所能得到的区间异或最大值。现在想办法求 和 ,考虑更新 。
易得 ,其中 可以这样求:因为 ,所以区间 的异或值等于 。所以求 转化为找 使得 最大。
在实际操作中可以 ,这样 就行了。
代码如下
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 500000;
int A[MAXN], N;
int maxleft[MAXN], maxright[MAXN];
int ne[20000000][2];
int nnodes;
void Insert(int x){
for(int bit = 30, node = 1; bit >= 0; bit--){
int dir = 0;
if((x & (1 << bit)) > 0) dir = 1;
if(ne[node][dir] == 0){
nnodes++;
ne[node][dir] = nnodes;
ne[nnodes][0] = ne[nnodes][1] = 0;
}
node = ne[node][dir];
}
}
int getmax(int x){//返回与 x 异或最大的数
int ans = 0;
for(int bit = 30, node = 1; bit >= 0; bit--){
int dir = 0;
if((x & (1 << bit)) > 0) dir = 1;
if(ne[node][1 - dir] > 0){
ans |= (1 << bit);
dir = 1 - dir;
}
node = ne[node][dir];
}
return ans;
}
int main(){
// freopen("xor.in","r",stdin);
// freopen("xor.out","w",stdout);
std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> N;
for(int i = 1; i <= N; i++){
cin >> A[i];
}
nnodes = 1;
ne[1][0] = ne[1][1] = 0;
Insert(0);
int i, sxor = 0;
maxleft[0] = 0;
//枚举 i,利用字典树,边插入边查询
for(int i = 1; i <= N; i++){//求前缀和
sxor ^= A[i];
maxleft[i] = getmax(sxor);
if(maxleft[i - 1] > maxleft[i]) maxleft[i] = maxleft[i - 1];
Insert(sxor);
}
nnodes = 1;
ne[1][0] = ne[1][1] = 0;
Insert(0);
sxor = 0;
maxright[N + 1] = 0;
for(int i = N; i >= 1; i--){//求前缀和
sxor ^= A[i];
maxright[i] = getmax(sxor);
if(maxright[i + 1] > maxright[i]) maxright[i] = maxright[i + 1];
Insert(sxor);
}
unsigned long long ans = 0, cans;
for(int i = 2; i <= N; i++){
cans = (unsigned long long)maxleft[i - 1] + (unsigned long long)maxright[i];
if(cans > ans) ans = cans;
}
cout << ans << endl;
return 0;
}