01Trie异或


一、01Trie维护异或极值

class Trie {
public:
    int no[MAXN][2] = { 0 };
    int tot = 0;
    void insert(int x) {
        int temp = 0;
        for (int i = 30; i >= 0; i--) {
            int num = (x >> i) & 1;
            if (!no[temp][num]) no[temp][num] = ++tot;
            temp = no[temp][num];
        }
    }
    //查找与x相异或最大的结果
    int get(int x) {
        int temp = 0;
        int data = 0;
        for (int i = 30; i >= 0; i--) {
            int num = (x >> i) & 1;
            if (!no[temp][num ^ 1]) {
                data |= (1 << i);
                temp = no[temp][num ^ 1];
            }
            else temp = no[temp][num];
        }
        return data;
     }
};

二、01Trie维护异或和(全局加1)


#include <iostream>
#include<vector>
#include<algorithm>

const int MAXN = 5e5 + 5;
using namespace std;
//维护异或极值
class Trie {
public:
    int no[MAXN][2] = { 0 };
    int w[MAXN] = { 0 };
    int wor[MAXN] = { 0 };
    int tot = 0;
    int hx = 30;
    void maintain(int o) {
        w[o] = wor[o] = 0;
        if (no[o][0]) {
            w[o] += w[no[o][0]];
            wor[o] |= wor[no[o][0]] << 1;
        }
        if (no[o][1]) {
            w[o] += w[no[o][1]];
            wor[o] ^= wor[no[o][1]] << 1;
            wor[o] |= w[no[o][1]] & 1;
        }
    }

    void insert(int x, int o, int h) {
        if (h > hx) {
            w[o]++;
            return;
        }
        if (!no[o][x & 1]) no[o][x & 1] = ++tot;
        insert(x >> 1, no[o][x & 1], h + 1);
        maintain(o);
    }
    void erase(int x, int o, int h) {
        if (h > hx) {
            w[o]--;
            return;
        }
        erase(x >> 1, no[o][x & 1], h + 1);
        maintain(o);
    }
    void addAll(int o) {
        swap(no[o][1], no[o][0]);
        if (no[o][0]) addAll(no[o][0]);
        maintain(o);
    }
};
Trie T;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    vector<int> a(n);
    int sum = 0, sum1 = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        T.insert(a[i], 0, 0);
        sum ^= a[i];
        sum1 ^= a[i] + 1;
    }
    cout << T.wor[0] << endl;
    cout << sum << endl;
    T.addAll(0);
    cout << T.wor[0] << endl;
    cout << sum1 << endl;
    return 0;
}

题目

BZOJ1954 最长异或路径
【Ynoi2010】Fusion tree
【luogu-P6623】树

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值