您的位置:首页 > 其它

Find MaxXorSum 字典树+DP

2016-07-22 20:47 253 查看
J - Find MaxXorSum
Time Limit:2000MS     Memory Limit:65535KB     64bit IO Format:
Submit Status

Description

Given n non-negative integers, you need to find two integers a and b that a xor b is maximum. xor is exclusive-or.

Input

Input starts with an integer T(T <= 10) denoting the number of tests. 

For each test case, the first line contains an integer n(n <= 100000), the next line contains a1, a2, a3, ......, an(0 <= ai <= 1000000000);

Output

For each test case, print you answer.

Sample Input

2
4
1 2 3 4
3
7 12 5


Sample Output

7
11


Hint


按二进制0,1建树,建好之后树上DP

#include<iostream>
#include<cstdio>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string.h>
#include<cstring>
#include<vector>
using namespace std;
#define INF 0x3f3f3f3f
#define mem(x,y) memset(x,y,sizeof(x))
typedef long long LL;
#define maxn 2222222
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int n,rear,root;
struct Node {
int son[2];//son【0】代表去往二进制的0位,son【1】同理
int x;//标记这个节点代表0,还是1
int ii;//标记这个节点是二进制的第几位
} node[maxn];
int tree_new() {
rear++;
node[rear].son[0]=node[rear].son[1]=node[rear].x=node[rear].ii=0;
return rear;
}
//初始化树
void tree_init() {
rear=0;
root=tree_new();
}
void tree_insert(int x) {
int rt=root;
for(int i=30; i>=0; i--) {//10亿共有31位01进制可用,
bool t=x&(1<<i);//第i位是1还是0,
if(node[rt].son[t]==0) node[rt].son[t]=tree_new();
rt=node[rt].son[t];
node[rt].ii=i;
node[rt].x=t;
// cout<<node[rt].x<<" ";
}
}
int dp(int rt0,int rt1) {//从根节点DP;
if(node[rt0].son[0]==0&&node[rt0].son[1]==0)
return node[rt0].x^node[rt1].x;
int max1=0,max2=0,t=((node[rt0].x^node[rt1].x)<<node[rt0].ii);
if(node[rt0].son[0]==0) return t+dp(node[rt0].son[1],node[rt1].son[node[rt1].son[0]?0:1]);
else  if(node[rt0].son[1]==0) return t+dp(node[rt0].son[0],node[rt1].son[node[rt1].son[1]?1:0]);
else if (node[rt1].son[1]==0) return t+dp(node[rt1].son[0],node[rt0].son[node[rt0].son[1]?1:0]);
else if (node[rt1].son[0]==0) return t+dp(node[rt1].son[1],node[rt0].son[node[rt0].son[0]?0:1]);
else  return t+max(dp(node[rt0].son[0],node[rt1].son[1]),dp(node[rt1].son[0],node[rt0].son[1]));
}
int main() {
//freopen("input.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--) {
tree_init();
scanf("%d",&n);
int a;
for(int i=0; i<n; i++) {
scanf("%d",&a);
tree_insert(a);
}
printf("%d\n",dp(root,root));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: