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] 有多少組 (i,j),i<j 滿足 s[j] xor 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章