题意:给出N个数,选出3个数ai,aj,ak(i != j != k)使(ai + aj) ^ ak 有最大值。
题解:暴力解法N^3据说也能过?正解是O(N^2), 首先对N个树建立字典树, 肯定是2进制位从高位到低位,很明显用栈非常方便,对数分解时,但是STL的栈竟然超时,具体实现看代码? 然后枚举2个数相加在树上找,注意这里先把枚举的两个数,从树上先删除在插入。然后就是很常规讨论下,是1最好最0,是0走1.
#include <bits/stdc++.h>
using namespace std;
#define SZ(X) ((int)X.size())
#define mp make_pair
#define pb push_back
#define RALL(X) X.rbegin(),X.rend()
#define ALL(X) X.begin(),X.end()
using ll = long long ;
using ld = long double ;
const int N = 2E5 + 7;
int tree[N][2];
int vis[N];
int a[1024], tot;
int sta[31];
void insert(int n)
{
int m = n;
int sz = 0;
while(m) {
sta[sz++] = m & 1;
m >>= 1;
}
while(sz < 31) sta[sz ++] = 0;
int now = 0;
while(sz) {
int top = sta[--sz] ;
if(!tree[now][top]) tree[now][top] = ++ tot;
now = tree[now][top];
vis[now] ++;
}
}
void erase(int n)
{
int m = n;
int sz = 0;
while(m) {
sta[sz++] = m & 1;
m >>= 1;
}
while(sz < 31) sta[sz ++] = 0;
int now = 0;
while(sz) {
int top = sta[--sz];
vis[tree[now][top]] --;
now = tree[now][top];
}
}
int tpow[32];
int solve(int n)
{
int m = n;
int sz = 0;
while(m) {
sta[sz++] = m & 1;
m >>= 1;
}
while(sz < 31) sta[sz ++] = 0;
int now = 0;
for(int i = 30;i >= 0;i --) {
int top = sta[i];
if(top == 0) {
if(vis[tree[now][1]]) {
n += tpow[i];
now = tree[now][1];
} else {
now = tree[now][0];
}
} else {
if(!vis[tree[now][0]]) {
n -= tpow[i];
now = tree[now][1];
} else {
now = tree[now][0];
}
}
}
return n;
}
int main()
{
std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cout << fixed;
int T;
tpow[0] = 1;
for(int i = 1; i <= 31; i ++) tpow[i] = tpow[i-1] * 2;
cin >> T;
while(T --) {
int n;
cin >> n;
for(int i = 1; i <= n; i ++) cin >> a[i];
tot = 0;
int ans = -1;
for(int i = 1; i <= n; i ++) insert(a[i]);
for(int i = 1; i <= n; i ++) {
erase(a[i]);
for(int j = i + 1; j <= n; j ++) {
int mmp = a[i] + a[j];
erase(a[j]);
ans = max(ans, solve(mmp)) ;
insert(a[j]);
}
insert(a[i]);
}
cout << ans << "\n";
for(int i = 0;i <= tot;i ++) {
tree[i][0] = tree[i][1] = vis[i] = 0;
}
}
return 0;
}