就直接贴代码了。ps: Trie里的next用vector的话会MLE,所以就改成了数组
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
ll nums[100010];
class Trie{
public:
Trie* next[2];
bool isNum;
Trie() {
next[0] = 0;
next[1] = 0;
isNum = false;
}
~Trie() {
del(this);
}
void add(ll num) {
Trie* curr = this;
for(int i = 31; i >= 0; i --) {
int bit = (num >> i) & 1;
if(!curr->next[bit]) {
curr->next[bit] = new Trie();
}
curr = curr->next[bit];
}
curr->isNum = true;
}
ll search_max(ll num) {
ll res = 0;
Trie* curr = this;
int target;
for(int i = 31; i >= 0; i --) {
res <<= 1;
int bit = (num >> i) & 1;
int rebit = 1-bit;
target = bit;
if(curr->isNum == true) return res;
if(curr->next[rebit]) {
res += 1;
target = rebit;
}
if(curr->isNum == false) curr = curr->next[target];
}
return res;
}
private:
void del(Trie* curr) {
for(auto ptr: curr->next) {
del(ptr);
}
delete curr;
}
};
int main() {
int n;
cin >> n;
ll res = 0;
Trie* t = new Trie();
for(int i = 1; i <= n; i ++) {
cin >> nums[i];
t->add(nums[i]);
}
for(int i = 1; i <= n; i ++) {
res = max(res, t->search_max(nums[i]));
}
cout << res << endl;
return 0;
}