CSU1216: 异或最大值(01Trie树)

Description

给定一些数,求这些数中两个数的异或值最大的那个值

Input

多组数据。第一行为数字个数n,1 <= n <= 10 ^ 5。接下来n行每行一个32位有符号非负整数。

Output

任意两数最大异或值

Sample Input

3
3
7
9

Sample Output

14

Hint

Source

CSGrandeur的数据结构习题

毒瘤老师给学弟们出这种题真的好么qwq。

难不成想让他们现场构造01trie这种数据结构?雾

#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long 
using namespace std;
const int MAXN = 1e5 + 10, B = 32;
int N, ch[MAXN][2], a[MAXN], tot;
void init() {
    memset(ch, 0, sizeof(ch));
    tot = 0;
}
void insert(LL x) {
    int now = 0;
    for(int i = B; i >= 0; i--) {
        bool nxt = (x >> i & 1);
        if(!ch[now][nxt]) ch[now][nxt] = ++tot;
        now = ch[now][nxt];
    }
}
LL Query(LL x) {
    LL now = 0, ret = 0;
    for(int i = B; i >= 0; i--) {
        bool nxt = (x >> i & 1) ^ 1;
        if(ch[now][nxt]) ret = ret | (1ll << i), now = ch[now][nxt];
        else now = ch[now][nxt ^ 1];
    }
    return ret;
}
int main() {
    //freopen("a.in", "r", stdin);
    while(~scanf("%d", &N)) {
        init();
        for(int i = 1; i <= N; i++) scanf("%d", &a[i]), insert(a[i]);
        LL ans = 0;
        for(int i = 1; i <= N; i++) ans = max(ans, Query(a[i]));
        printf("%lld
", ans);
    }
    return 0;
}
/**********************************************************************
    Problem: 1216
    User: attack
    Language: C++
    Result: AC
    Time:124 ms
    Memory:2292 kb
**********************************************************************/
原文地址:https://www.cnblogs.com/zwfymqz/p/9320572.html