One day, ZS the Coder wrote down an array of integers a with elements a1, a2, …, an.
A subarray of the array a is a sequence al, al + 1, …, ar for some integers (l, r) such that 1 ≤ l ≤ r ≤ n. ZS the Coder thinks that a subarray of a is beautiful if the bitwise xor of all the elements in the subarray is at least k.
Help ZS the Coder find the number of beautiful subarrays of a!
求异或值大于给定K的区间个数。
xor运算 有 a xor a=0的性质
所以我们可以考虑求区间前缀和。问题转化为对于
s[1]..s[n]
s
[
1
]
.
.
s
[
n
]
有多少组
(i,j),i<j
(
i
,
j
)
,
i
<
j
满足
s[j]
s
[
j
]
xor
x
o
r
s[i]>=k
s
[
i
]
>=
k
.
xor问题可考虑01trie树。。
每个节点存,在这个节点下面有多少数。
每插入一个数在trie树查询一下答案,分类讨论计算答案。
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e6+5;
const int N=1<<25;
#define ll long long
int n,k,v[MAXN],sum[MAXN],d[35];
struct trie{
int c[N][2],w[N],cnt;
void insert(int pos,int val,int dep){
if(dep==30)return;
int which=((val&(d[dep+1]))>0)?1:0;
if(!c[pos][which])c[pos][which]=++cnt;
w[c[pos][which]]++;
insert(c[pos][which],val,dep+1);
}
ll query(int pos,int val,int dep){
ll ans=0;
if(!pos)return 0;
if(dep==30)return w[pos];
if(((val&(d[dep+1]))>0)?1:0){
if(k&d[dep+1])ans+=query(c[pos][0],val,dep+1);
else ans+=w[c[pos][0]]+query(c[pos][1],val,dep+1);
}
else {
if(k&d[dep+1])ans+=query(c[pos][1],val,dep+1);
else ans+=w[c[pos][1]]+query(c[pos][0],val,dep+1);
}
return ans;
}
}T;
int main(){
// freopen("1.out","w",stdout);
T.cnt=1;
d[30]=1;
for(int i=29;i>=0;i--)d[i]=d[i+1]<<1;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",&v[i]);
sum[i]=sum[i-1]^v[i];
}
ll ans=0;
for(int i=1;i<=n;i++){
T.insert(1,sum[i-1],0);
ans+=T.query(1,sum[i],0);
}
// for(int i=1;i<=50;i++)cout<<T.w[i];
printf("%I64d\n",ans);
return 0;
}