NBUT1597:Find MaxXorSum(字典树)

本文介绍了一道名为FindMaxXorSum的问题,该问题要求从给定的非负整数中找出两数异或的最大值。通过构建字典树来存储所有数的二进制形式,并遍历这些数来寻找最大异或值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • [1597] Find MaxXorSum

  • 时间限制: 2000 ms 内存限制: 65535 K
  • 问题描述
  • 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 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);
  • 输出
  • For each test case, print you answer.
  • 样例输入
  • 2
    4
    1 2 3 4
    3
    7 12 5
  • 样例输出
  • 7
    11
  • 提示
  • 来源
  • Alex@NBUT
题意:给N个数,求其中两个数异或的最大值。

思路:字典树,将N个数的二进制存到树里,然后再遍历N个数,找到异或的最大值。

# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# define ll long long
using namespace std;
const int maxn = 1e5;

ll a[maxn+3], cnt=0;
struct node
{
    int next[2];
}tri[maxn*13];//乘以13即可,待证。

void add(ll x)
{
    int cur = 0;
    for(int i=31; i>=0; --i)//题目数据范围为32位整型。
    {
        int t = (x>>i)&1;
        if(!tri[cur].next[t])
            tri[cur].next[t] = ++cnt;
        cur = tri[cur].next[t];
    }
}

ll query(ll x)
{
    int cur = 0;
    ll tmp = 0;
    for(int i=31; i>=0; --i)
    {
        int t = !((x>>i)&1);//找到相反的,因为不同的异或值为1。
        if(tri[cur].next[t])
        {
            tmp |= (1<<i);
            cur = tri[cur].next[t];
        }
        else
            cur = tri[cur].next[!t];
    }
    return tmp;
}

int main()
{
    int t, n;
    scanf("%d",&t);
    while(t--)
    {
        cnt = 0;
        scanf("%d",&n);
        memset(tri, 0, sizeof(tri));
        for(int i=1; i<=n; ++i)
        {
            scanf("%lld",&a[i]);
            add(a[i]);
        }
        ll ans = 0;
        for(int i=1; i<=n; ++i)
            ans = max(ans, query(a[i]));
        printf("%lld\n",ans);
    }
    return 0;
}


转载于:https://www.cnblogs.com/junior19/p/6729889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值