Edu12 Beautiful Subarrays --- 题解

 Beautiful Subarrays:

题目大意:

  思路解析:

要找到一个区间并且区间的l--r里面所有的元素异或值大于等于k,称这样的数组是优美子数组,问优美子数组有多少个。

[L,R] 的数组异或和等价于 (a1,a2,a3,....aL-1) ^ (a1,a2,a3,a4,....aR)那么发现我们可以用前缀和的思想,来找到一个前缀使得[L,R]是优美子数组,发现这种二进制的寻找可以利用字典树实现,然后每次在这样的字典树插入前缀。

寻找时,如果加上当前位就能大于等于k,那么我们并不用关心以后的情况了,直接加上满足能加上当前位的所有情况即可,这里需要利用一个标记位进行预处理。

代码实现:


#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 3e7 + 5;
int ch[maxn][2];
int tag[maxn];
int tot = 0;
ll ans = 0;
int k;
void insert(int x){
    int p = 0;
    tag[p]++;
    for (int i = 30; i >= 0; i--) {
        int c = (x >> i) & 1;
        if (ch[p][c] == 0) ch[p][c] = ++tot;
        p = ch[p][c];
        tag[p]++;
    }
}

void get(int x){
    int cur = 0;
    int p = 0;
    for (int j = 30; j >= 0; j--) {

        int c = (x >> j) & 1;
        if ((cur | (1 << j)) >= k){
            ans += ch[p][c ^ 1] != 0 ? tag[ch[p][c ^ 1]] : 0;
            p = ch[p][c];
        }else {
            cur |= (1 << j);
            p = ch[p][c ^ 1];
        }
        if (p == 0) break;
    }
    if (cur >= k) ans += p != 0 ?tag[p]:0;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    memset(ch, 0, sizeof(ch));
    memset(tag, 0, sizeof(ch));
    int n;
    cin >> n >> k;
    int s = 0;
    insert(s);
    for(int i = 0; i < n; ++i){
        int num;
        cin >> num;
        s ^= num;
        get(s);
        insert(s);
    }
    cout << ans << endl;
    return 0;
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Studying~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值