Educational Codeforces Round 12 E trie树

来源:互联网 发布:mac百度网盘配置svn 编辑:程序博客网 时间:2024/06/05 07:03



链接:戳这里


E. Beautiful Subarrays
time limit per test3 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
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!

Input
The first line contains two integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 109) — the number of elements in the array a and the value of the parameter k.

The second line contains n integers ai (0 ≤ ai ≤ 109) — the elements of the array a.

Output
Print the only integer c — the number of beautiful subarrays of the array a.

Examples
input
3 1
1 2 3
output
5
input
3 2
1 2 3
output
3
input
3 3
1 2 3
output
2


题意:

长度为n的整数序列,询问有多少区间[l,r](1<=l<=r<=n),满足区间抑或和>=k


思路:

区间[l,r]抑或和sum[l,r]=sum[1,l-1]^sum[1,r],问题简化成,[1,n]的前缀抑或和,任选两个数满足抑或和>=k

考虑Trie树,以k为主干在trie树上跑

如果当前k位置为1,则表示询问的数(x>>i&1)必须0才能统计贡献

如果当前k位置为0,则表示询问的数(x>>i&1)对立面的满足情况的num都要统计上


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<string>#include<vector>#include <ctime>#include<queue>#include<set>#include<map>#include<list>#include<stack>#include<iomanip>#include<cmath>#include<bitset>#define mst(ss,b) memset((ss),(b),sizeof(ss))///#pragma comment(linker, "/STACK:102400000,102400000")typedef long long ll;typedef long double ld;#define INF (1ll<<60)-1#define Max 31*1000005using namespace std;int n,k,x;int num[Max],cnt=1;int d[Max][2];void update(int x){    int p=1;    for(int i=30;i>=0;i--){        if(d[p][(x>>i)&1]==0) d[p][(x>>i)&1]=++cnt;        p=d[p][(x>>i)&1];        num[p]++;    }}ll query(int x){    ll ans=0;    int p=1;    for(int i=30;i>=0;i--){        if(p==0) break;        int t=(k>>i)&1;        if(t){            p=d[p][1^((x>>i)&1)];        } else {            ans+=num[d[p][1^((x>>i)&1)]];            p=d[p][(x>>i)&1];        }    }    return ans+num[p];}int main(){    scanf("%d%d",&n,&k);    int sum=0;    ll ans=0;    for(int i=1;i<=n;i++){        update(sum);        scanf("%d",&x);        sum^=x;        ans+=query(sum);    }    printf("%I64d\n",ans);    return 0;}


0 0
原创粉丝点击