Find MaxXorSum 字典树+DP

J - Find MaxXorSum
Time Limit:2000MS     Memory Limit:65535KB     64bit IO Format:

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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值