This documentation is automatically generated by online-judge-tools/verification-helper
#include "data_structure/binary_trie.hpp"定义于头文件 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);
#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;
}
}
};