cf 665E - Beautiful Subarrays

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值