题目:Chip Factory
题解:这题其实用暴力是可以解决的。但我是为了练习01字典树。先将n个数组建成一个01字典树,我是用num数组来统计有多少个数经过某个结点。然后来一个双重循环,计算(a[i]+a[j]),但题目要求i,j,k不能相等,所以需要在上面建的树,将第i个数和第j个数删点,这时候就用num数组了,将经过第i个数和第j个数的结点都进行-1。然后在树中找最大值的时候num[x]为0的话,说明已经走不下去了。
#include <cstdio>
#include <stack>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1e3+10;
typedef long long ll;
ll a[N];
int cnt;
int num[N*35];
int tree[N*35][2];
//2000000000 31位
void insert(ll y){
int p = 1;
for(int i = 32;i >= 0;i--){
int x = (y>>i)&1;
if(!tree[p][x]) {
tree[p][x] = ++cnt;
}
num[tree[p][x]]++;
p = tree[p][x];
}
}
ll query(ll y){
int p = 1;
ll ans = 0;
for(int i = 32;i >= 0;i--){
int x = (y>>i)&1;
if(tree[p][x^1] && num[tree[p][x^1]]) {
ans = ans*2+1;
p = tree[p][x^1];
}
else if(num[tree[p][x^0]]){
ans = ans*2;
p = tree[p][x^0];
}
}
return ans;
}
void update(ll y,int c){
int p = 1;
for(int i = 32;i >= 0;i--){
int x = (y>>i)&1;
num[tree[p][x]] += c;
p = tree[p][x];
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n;
cnt = 1;
memset(num,0,sizeof num);
memset(tree,0,sizeof tree);
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%lld",&a[i]);
insert(a[i]);
}
/*
for(int i = 0;i < 40;i++){
cout<<i<<" "<<num[i][0]<<" "<<num[i][1]<<endl;
}
*/
ll ans = 0;
for(int i = 1;i <= n;i++){
update(a[i],-1);
for(int j = i+1;j <= n;j++){
update(a[j],-1);
ans = max(ans,query(a[i]+a[j]));
update(a[j],1);
}
update(a[i],1);
}
cout<<ans<<endl;
}
return 0;
}