The XOR Largest Pair(算法竞赛进阶指南 P72,Trie)

一.题目链接:

The XOR Largest Pair

二.题目大意:

有 n 个数,求任意两个数异或得到的最大值.

三.分析:

刚学习了字典树,觉得还不错.

把每个数分解为二进制存到字典树中,查询即可.

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long
#define ull unsigned long long
using namespace std;

const int M = (int)1e5;
const int mod = 99991;
const int inf = 0x3f3f3f3f;

int x, ans = -inf;
int cnt = 1;
int trie[M * 50 + 5][2];

void Insert()
{
    int p = 1;
    for(int i = 30; i >= 0; --i)
    {
        bool v = (x>>i) & 1;
        if(!trie[p][v])
            trie[p][v] = ++cnt;
        p = trie[p][v];
    }
}

int Query()
{
    int p = 1;
    int res = 0;
    for(int i = 30; i >= 0; --i)
    {
        int v = (x>>i) & 1;
        if(trie[p][!v])
        {
            res |= (1<<i);
            p = trie[p][!v];
        }
        else
            p = trie[p][v];
    }
    return res;
}

int main()
{
    int n;
    scanf("%d", &n);
    while((n--) > 0)
    {
        scanf("%d", &x);
        ans = max(ans, Query());
        Insert();
    }
    printf("%d\n", ans);
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值