Find MaxXorSum NBUT - 1597(字典树)

点击打开链接

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
题意:给出n个整数,要求n个数里面找出两个数,那两个数的亦或值最大。

一开始写了一个自认为很有道理的贪心,找出最大和次大的两个值,最大的亦或值一定是这两个数和其他数的亦或,天真的以为最大和次大的两个数的二进制长度一定最长,wa了两发之后被学长一个样例就推翻了(太丢脸了2333)

下面讲一下正确的解法:

最大亦或值,我们首先想到的是二进制,所以要把n个数变成二进制存进字典树里面,然后在树上dp就可以了


#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
#include<set>
#include<stdlib.h>
#include<queue>
#include<vector>
#include<math.h>
using namespace std;
typedef long long ll;
int tot;
struct Trie{
    int nxt[2];
    void init(){
        memset(nxt , -1 , sizeof(nxt));
    }
}L[2000000];//字典树
void add(int x){
    int p = 0;
    for(int i = 30 ; i >= 0 ;){
        bool v = x&(1<<i);//数字的二进制当前位置为0还是1
        if(L[p].nxt[v] == -1){
            L[tot].init() ;
            L[p].nxt[v] = tot++;
        }
        p = L[p].nxt[v];
        i--;
    }
}
int query(int x){//查询
    int p = 0;
    int ans = 0;
    for(int i = 30 ; i >=0 ; ){
        bool v = x&(1<<i);
        if(L[p].nxt[!v] == -1){
            p = L[p].nxt[v];
        }
        else{
            p = L[p].nxt[!v];
            ans += (1<<i) ;
            //cout<<ans<<endl;
        }
        i--;
    }
    return ans ;
}
int aa[100005];
int main()
{
    int t , n;
    scanf("%d",&t);
    while(t--){
        tot = 1 ;
        L[0].init();
        scanf("%d",&n);
        for(int i = 0 ; i < n ; i ++){
            scanf("%d",&aa[i]);
            add(aa[i]);
        }
        int ans = 0;
        for(int i = 0 ; i < n ; i ++)
            ans = max(ans , query(aa[i]));
       printf("%d\n",ans);
    }
    return 0;
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值