码迷,mamicode.com
首页 > Windows程序 > 详细

AcWing 143. 最大异或对

时间:2019-04-30 17:18:27      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:http   search   amp   break   run   out   node   include   namespace   

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. 最大异或对

标签:http   search   amp   break   run   out   node   include   namespace   

原文地址:https://www.cnblogs.com/polystyrene/p/10796811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!