【NBUT - 1597 Find MaxXorSum】 字典树

G - Find MaxXorSum

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
 
 
题意:给出n个数字,找出其中两个数字异或(^)的最大值。
 
 
分析:可以把数字拆成二进制,构建字典树,添加进数字后,遍历n个数寻找异或的最大值。
0 ^ 1 = 1
1 ^ 0 = 1
0 ^ 0 = 0
1 ^ 1 = 0
所以可以在查找的时候先把二进制数求非(!),然后在字典树中查找是否有这一位,再用或(|)转为十进制得到答案。
 
 
代码如下:
#include <set>
#include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MX 100005
#define mod 835672545
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
int n, tot;
LL a[MX];
struct node{
    int nxt[2];
}tree[MX*13];
void add(LL x){
    int now = 0;
    for(int i = 31; i >= 0; i--){
        int t = (x >> i)&1;
        if(tree[now].nxt[t] == 0){
            tree[now].nxt[t] = ++tot;
        }
        now = tree[now].nxt[t];
    }
}
LL query(LL x){
    int now = 0;
    LL ans = 0;
    for(int i = 31; i >= 0; i--){
        int t = !((x >> i)&1);
        if(tree[now].nxt[t] != 0){
            ans |= (1 << i);
            now = tree[now].nxt[t];
        }
        else now = tree[now].nxt[!t];
    }
    return ans;
}
int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        tot = 0;
        memset(tree, 0, sizeof(tree));
        scanf("%d", &n);
        for(int i = 0; i < n; i++){
            scanf("%I64d", &a[i]);
            add(a[i]);
        }
        LL ans = 0;
        for(int i = 0; i < n; i++){
            ans = max(ans, query(a[i]));
        }
        printf("%I64d\n", ans);
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值