The XOR Largest Pair

The XOR Largest Pair

https://ac.nowcoder.com/acm/problem/50993

The XOR Largest Pair

题目描述

给定一串长度为 序列,问序列中的两个数异或值最大是多少

分析

不难发现,要让两个数的异或值尽可能的大,就是要让两个数在二进制下 从高位到低位 尽可能的不同
比如一个数是这样的 ,那么在 中与这个数异或值最大的数就是
考虑建一棵 字典树,对每一个数字进行一次插入和查询的操作,用每次查询的结果更新一下答案即可

插入操作
首先,对于一棵字典树,我是默认的 为根,然后把数一个一个插入到字典树中,大概长成这个样子

图片来源
就是把字符换成 ,根换成 ,就和我说的没啥区别了
然后就会发现,从根到叶子节点的信息就可以表示出原来的数的情况了

inline void Insert()
{
    int p(0);
    for (int i = 30; ~i; --i) {
        int sta = (temp >> i) & 1;
        if (!son[p][sta]) son[p][sta] = ++id;
        p = son[p][sta];
    }
}

查询操作
前面有提到说要从最高位开始贪心,易证第 位后所有的 的贡献权值之和没有第 位一个
就是说,如果这一位的异或后可以有贡献,那么就走与这一位不相同的方向
否则就走和原来相同的方向
如果此时已经是空节点了,然后就可以返回了

inline void find()
{
    int p(0), res(0);
    for (int i = 30; ~i; --i) {
        int sta = (temp >> i) & 1;
        if (son[p][sta ^ 1]) p = son[p][sta ^ 1], res |= 1 << i;
        else if (son[p][sta]) p = son[p][sta];
        else break;
    }
    if (res > ans) ans = res;
}

Code

#include <cstdio>

const int maxn = 1e5 + 10;
int n, id, ans, temp;
int son[maxn * 32][2];

inline int __read()
{
    int x(0), t(1);
    char o (getchar());
    while (o < '0' || o > '9') {
        if (o == '-') t = -1;
        o = getchar();
    }
    for (; o >= '0' && o <= '9'; o = getchar()) {
        x = (x << 1) + (x << 3) + (o ^ 48);
    }
    return x * t;
}

inline void Insert()
{
    int p(0);
    for (int i = 30; ~i; --i) {
        int sta = (temp >> i) & 1;
        if (!son[p][sta]) son[p][sta] = ++id;
        p = son[p][sta];
    }
}

inline void find()
{
    int p(0), res(0);
    for (int i = 30; ~i; --i) {
        int sta = (temp >> i) & 1;
        if (son[p][sta ^ 1]) p = son[p][sta ^ 1], res |= 1 << i;
        else if (son[p][sta]) p = son[p][sta];
        else break;
    }
    if (res > ans) ans = res;
}

int main()
{
    n = __read();
    for (int i = 1; i <= n; ++i) {
        temp = __read();
        Insert();
        find();
    }
    printf ("%d\n", ans);
}
全部评论

相关推荐

点赞 评论 收藏
转发
4 2 评论
分享
牛客网
牛客企业服务