題目: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;
}