一、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];
}
}
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】树