ContinueLib

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Continue765/ContinueLib

:heavy_check_mark: BinaryTrie
(data_structure/binary_trie.hpp)

BinaryTrie

定义于头文件 binary_trie.hpp

struct BinaryTrie;

维护 $[0, 2^{31})$ 内整数的可重集,支持插入、删除与最大异或查询,单次操作 $O(\log V)$,$V = 2^{31}$。

成员函数

构造

成员函数 说明
BinaryTrie(int n = 0) 分配大小为 $n$ 的结点池,下标 $1$ 为根结点

修改

成员函数 说明
void insert(int x) 插入一个 $x$
void erase(int x) 删除一个 $x$

查询

成员函数 说明
int query(int x) 返回集合中与 $x$ 异或的最大值

示例

BinaryTrie trie(n);
trie.insert(3);
trie.insert(5);
int mx = trie.query(4);
trie.erase(3);

Depends on

Verified with

Code

#pragma once
#include <common.hpp>


struct BinaryTrie {
    struct Node {
        array<int, 2> ch;
        int end;
        Node() {
            ch[0] = ch[1] = 0;
            end = 0;
        }
    };

    vector<Node> tr;
    int tot;

    BinaryTrie(int n = 0) : tr(n), tot(1) {}

    void insert(int x) {
        int p = 1;
        for (int i = 30; i >= 0; i--) {
            int c = x >> i & 1;
            if (!tr[p].ch[c]) {
                ++tot;
                tr[p].ch[c] = tot;
            }
            p = tr[p].ch[c];
            tr[p].end++;
        }
    }

    int query(int x) {
        int p = 1, res = 0;
        for (int i = 30; i >= 0; i--) {
            int c = x >> i & 1;
            if (tr[p].ch[c ^ 1]) {
                res |= (1 << i);
                p = tr[p].ch[c ^ 1];
            } else {
                p = tr[p].ch[c];
            }
        }
        return res;
    }

    void erase(int x) {
        int p = 1;
        for (int i = 30; i >= 0; i--) {
            int c = x >> i & 1;
            int nxt = tr[p].ch[c];
            tr[nxt].end--;
            if (tr[nxt].end == 0) {
                 tr[p].ch[c] = 0;
            }
            p = nxt;
        }
    }
};
Back to top page