PS

BOJ 13505 : 두 수 XOR

lickelon 2024. 10. 18. 22:16
  • 문제 링크 : boj.kr/13505
  • 난이도 : P3
  • 태그 : 트라이

코드

#include <bits/stdc++.h>

#define all(x) (x).begin(), (x).end()

#define INF 0x7FFFFFFF

using namespace std;

using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;

class Trie {
public:
    Trie* children[2];
    bool end;

    Trie() : end(false) {children[0] = children[1] = NULL;}

    void insert(vector<int>& key) {
        this->_insert(key, 0);
    };
    int find(vector<int>& key) {
        return this->_find(key, 0, 0);
    };

private:
    void _insert(vector<int>& key, int index) {
        if(index == key.size()) {
            end = true;
            return;
        }
        int next = key[index];
        if(children[next] == NULL) children[next] = new Trie();
        children[next]->_insert(key, index + 1);
    }
    int _find(vector<int>& key, int depth, int num) {
        int ret;
        int next = key[depth];
        if(children[!next] == NULL) ret = next;
        else {
            ret = !next;
            next = !next;
        }
        if(depth == key.size()) return num;
        return children[next]->_find(key, depth + 1, num*2 + ret);
    }
};

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n;
    cin >> n;

    Trie root;
    int ans = 0;
    for(int i = 0; i < n; i++) {
        int input;
        cin >> input;
        bitset<31> bs(input);
        vector<int> arr(31);
        for(int i = 0; i < 31; i++) {
            arr[i] = bs[i];
        }
        reverse(all(arr));
        root.insert(arr);
        int f = root.find(arr);
        ans = max(ans, input ^ root.find(arr));
    }
    cout << ans << "\n";

    return 0;
}

풀이

트라이에 저장된 수들 중 자신과 XOR한 값이 가장 큰 값을 찾아 XOR한다.

'PS' 카테고리의 다른 글

BOJ 17306 : 전쟁 중의 삶  (2) 2024.10.20
BOJ 6073 : Secret Message  (0) 2024.10.19
BOJ 13504 : XOR 합  (0) 2024.10.17
BOJ 19585 : 전설  (1) 2024.10.17
BOJ 5446 : 용량 부족  (1) 2024.10.15