题意
给定一个 n n n 个数的数组,要求找一个连续子区间,满足该子区间的区间 & \& &和大于区间异或和。求该子区间的最大长度。
思路
出现了按位与和按位异或,那么我们首先从二进制位考虑。
区间 a n d > x o r \rm and>xor and>xor,则他们的最高位二进制一定相同且长度为偶数:因为长度为奇数时对于任意位 d d d,若子区间第 d d d 位全为 1 1 1则异或和也为 1 1 1,不优;而若至少有一个位置第 d d d位为 0 0 0则该位按位与为 0 0 0,不优。
那么,一个区间能满足区间与大于区间异或的充要条件是:
- 区间长度为偶数。
- 区间从高到低第 x x x位全为 1 1 1。
- 区间从高到低前 x − 1 x-1 x−1位每一位上 1 1 1的个数都是偶数个。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int n,ans,a[N],pr[N],buc[2][1<<20];
int main(){
cin>>n;
for(int i=1;i<=n;i++)scanf("%d",&a[i]),pr[i]=a[i]^pr[i-1];
for(int i=20;~i;i--){
memset(buc,-1,sizeof(buc));
for(int j=1,r=1;j<=n;r=j=r+1){
if((a[j]>>i&1)==0)continue;
while(r<n&&(a[r+1]>>i&1))r++;
for(int k=j-1;k<=r;k++){
int res=pr[k]>>i+1;
if(buc[k&1][res]==-1)buc[k&1][res]=k;
else ans=max(ans,k-buc[k&1][res]);
} for(int k=j-1;k<=r;k++)buc[k&1][pr[k]>>i+1]=-1;
}
} cout<<ans<<endl;
return 0;
}