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\n", ans);
    }
    return 0;
}
/**********************************************************************
    Problem: 1216
    User: attack
    Language: C++
    Result: AC
    Time:124 ms
    Memory:2292 kb
**********************************************************************/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM