AcWing 143. 最大异或对

Posted polystyrene

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AcWing 143. 最大异或对相关的知识,希望对你有一定的参考价值。

https://www.acwing.com/problem/content/145

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 100010;
int n;
int a[N];

class TrieNode {
public:
    TrieNode() {};
    TrieNode* children[2];
};

class Trie {
public:
    Trie() {
        root = new TrieNode;
    }
    
    void insert(int x) {
        TrieNode* cur = root;
        for (int i = 30; i >= 0; i--) {
            int c = x >> i & 1;
            if (!cur->children[c]) {
                cur->children[c] = new TrieNode;
            }
            cur = cur->children[c];
        }
    }

    int search(int x) {
        TrieNode* cur = root;
        
        int res = 0;
        for (int i = 30; i >= 0; i--) {
            int c = x >> i & 1;
            if (cur->children[!c]) {
                res += 1 << i;
                cur = cur->children[!c];
            } else if (cur->children[c]) {
                cur = cur->children[c];
            } else {
                break;
            }
        }
        return res;
    }
private:
    TrieNode* root;
};

int run() {
    Trie trie;
    int res = 0;
    for (int i = 0; i < n; i++) {
        trie.insert(a[i]);
        res = max(res, trie.search(a[i]));
    }

    return res;
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    cout << run() << endl;
    return 0;
}

 

以上是关于AcWing 143. 最大异或对的主要内容,如果未能解决你的问题,请参考以下文章

AcWing 143. 最大异或对

AcWing 143. 最大异或对

AcWing 143. 最大异或对

AcWing 143. 最大异或对

AcWing 143 最大异或对

AcWing 143. 最大异或对 (异或性质,Trie)