1. 程式人生 > 其它 >acwing-143. 最大異或對

acwing-143. 最大異或對

在給定的 N 個整數 A1,A2……AN 中選出兩個進行 xor(異或)運算,得到的結果最大是多少?

輸入格式

第一行輸入一個整數 N。

第二行輸入 N 個整數 A1~AN。

輸出格式

輸出一個整數表示答案。

資料範圍

1≤N≤105,
0≤Ai<231

輸入樣例:

3
1 2 3

輸出樣例:

3

方法一:

字典樹模板題2,使用貪心的思想,從二進位制高位到低位,儘量找當前位相反的位(根據異或的運算性質,相反的位異或=1)

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
const int M = 1 << 30;

int n, trie[N * 32 + 10][2], idx, cnt[N*32+10], nums[N];

void insert(int a) {
    int m = M, p = 0;
    for (int i = 0; i < 31; ++i, m>>=1) {
        int b = (a & m) != 0;
        if (!trie[p][b]) trie[p][b] = ++idx;
        p = trie[p][b];
    }
    cnt[p] = 1;
}

int getmax(int a) {
    int m = M, p = 0, res = 0;
    for (int i = 0; i < 31; ++i, m>>=1) {
        int b = a & m;
        if (trie[p][!b]) {
            res += m;
            p = trie[p][!b];
        } else {
            p = trie[p][b!=0];
        }
    }
    return res;
}

int main() {
    int a;
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &nums[i]);
        insert(nums[i]);
    }
    int res = 0;
    for (int i = 0; i < n; ++i) {
        res = max(res, getmax(nums[i]));
    }
    printf("%d", res);
}