[Trie、贪心] Acwing143. 最大异或对
题意:输入n个数,选出异或最大的一对
暴力\(O(n^{2})\):枚举每一对
优化:把每个数转化成01串插入trie,枚举每个数,在trie中从高位到低位寻找每一位尽量与它不同的字符串,这样时间复杂度就优化到了\(O(n)\)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int n, t;
int son[maxn][2], idx, ans;
vector<vector<int> > a;
void insert(vector<int> v) {
int p = 0;
for (auto u:v) {
if (!son[p][u]) son[p][u] = ++idx;
p = son[p][u];
}
}
int solve(vector<int> v) {
int p = 0, r = 31, ans = 0;
for (auto u:v) {
r--;
if (son[p][!u]) {
p = son[p][!u];
u = !u;
ans += 1 << r;
}
else p = son[p][u];
}
return ans;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> t;
vector<int> v;
for (int i = 1; i <= 31; i++) {
v.push_back(t & 1);
t >>= 1;
}
reverse(v.begin(), v.end());
insert(v);
a.push_back(v);
}
for (auto v:a) ans = max(ans, solve(v));
cout << ans;
return 0;
}