zoukankan      html  css  js  c++  java
  • 「字典树」最大异或对

    最大异或对

    原题链接:最大异或对

    题目大意

    给你(n)个数,从中选两个数进行异或运算,得到结果最大是多少

    题目题解

    一道没写过就不知道怎么写的套路题

    刚开始可以用贪心分析,也就是说如果两个数的高位能够尽可能的大那么我们就尽可能的大就好了,也就是说两个数的二进制数在同一位不同,此时最大,那么怎样很快的满足呢?我们发现可以将二进制数转化到Trie上面解决,当前是1就尽可能走0,当前是0就尽可能走1,那这个问题就很简单了,建个Trie数直接跑就好了

    //#define fre yes
    
    #include <cstdio>
    #include <iostream>
    
    const int N = 100005;
    struct Node {
        int son[2];
    } trie[N * 30];
    int a[N], idx;
    
    void Insert(int x) {
        int rt = 0;
        for (int i = 30; i >= 0; i--) {
            int id = x >> i & 1;
            if(!trie[rt].son[id]) trie[rt].son[id] = ++idx;
            rt = trie[rt].son[id];
        }
    }
    
    int Search(int x) {
        int rt = 0, ans = 0;
        for (int i = 30; i >= 0; i--) {
            int id = x >> i & 1;
            if(trie[rt].son[!id]) {
                rt = trie[rt].son[!id];
                ans += (1 << i);
            } else rt = trie[rt].son[id];
        } return ans;
    }
    
    int main() {
        static int n, ans;
        scanf("%d", &n);
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            Insert(a[i]);
        } for (int i = 1; i <= n; i++) ans = std::max(ans , Search(a[i]));
        printf("%d
    ", ans);
        return 0;
    }
    
  • 相关阅读:
    [LeetCode]Reverse Linked List II
    [LeetCode]Move Zeroes
    Next Greater Element I
    Keyboard Row
    Number Complement
    SQL语句学习(二)
    SQL语句学习(一)
    jQuery学习(三)
    jQuery学习(二)
    JQuery学习(一)
  • 原文地址:https://www.cnblogs.com/Nicoppa/p/11526192.html
Copyright © 2011-2022 走看看