P5283 [十二省联考2019]异或粽子 【前缀异或+可持久化Trie+优先队列】

传送门

解题思路:区间的的异或和我们利用前缀异或来处理 xor[l,r] = prefix[r] \wedge prefix[l-1]
这道题和超级钢琴十分类似,只是转化成立异或,我们可以利用Tire来解决问题,因为要多次询问区间第K大异或,我们利用可持久化Trie来维护前缀异或和。我们固定区间的右端点,把每个每个区间的异或最大值放于堆中去维护,每当我们取出一个数后,我们往堆里面放入下一个异或最大值。类似再Trie树上询问区间第K大异或。

代码:

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
const int maxn = 5e5 + 5;

int n, k;
ll pre[maxn], x;
struct node {
    int ls, rs, cnt0, cnt1;    ///ls为0 ,rs为1
} p[maxn * 80];
int root[maxn], times;

struct state {
    int pos, k;
    ll maxn;  

    bool friend operator<(state a, state b) {
        return a.maxn < b.maxn;
    }
} temp;

void insert(int &now, int old, int pos, ll x) {
    if (pos == -1) return;
    now = ++times;
    p[now] = p[old];
    if (x >> pos & 1) {
        p[now].cnt1++;
        insert(p[now].rs, p[old].rs, pos - 1, x);
    } else {
        p[now].cnt0++;
        insert(p[now].ls, p[old].ls, pos - 1, x);
    }
}

ll query(int now, int pos, ll x, int k) {       ///Trie 上询问第K大异或
    if (pos == -1) return 0;
    if (x >> pos & 1) {
        if (k <= p[now].cnt0) return query(p[now].ls, pos - 1, x, k);
        else return query(p[now].rs, pos - 1, x, k - p[now].cnt0) + (1LL << pos);
    } else {
        if (k <= p[now].cnt1) return (1LL << pos) + query(p[now].rs, pos - 1, x, k);
        else return query(p[now].ls, pos - 1, x, k - p[now].cnt1);
    }
}

int main() {
    ll ans = 0;
    scanf("%d %d", &n, &k);
    insert(root[0], root[0], 34, 0);
    for (int i = 1; i <= n; i++) {
        scanf("%lld", &x);
        pre[i] = pre[i - 1] ^ x;
        insert(root[i], root[i - 1], 34, pre[i]);
    }
    priority_queue<state> q;
    for (int i = 1; i <= n; i++) {
        temp.pos = i, temp.k = 1;
        temp.maxn = pre[i] ^ query(root[i - 1], 34, pre[i], 1);
        q.push(temp);
    }
    while (k--) {
        temp = q.top(), q.pop();
        ans += temp.maxn;
        if (temp.pos == temp.k) continue;
        temp.maxn = pre[temp.pos] ^ query(root[temp.pos], 34, pre[temp.pos], ++temp.k);
        q.push(temp);
    }
    printf("%lld\n", ans);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值