Educational Codeforces Round 12 E trie树

本文介绍了一种利用前缀异或和与Trie树解决特定区间查询问题的方法,即找出数组中所有满足条件的子数组,这些子数组的异或和大于等于给定阈值k。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



链接:戳这里


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*1000005
using 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值