Tuesday, March 14, 2023

Reduce the Array [DSA Coding Contest - March 23]

#include "bits/stdc++.h"
using namespace std;
#define int     long long int
#define endl    '\n'
 
struct Trie {
    int counter;
    Trie *child[2];
 
    Trie() {
        counter = 0;
        for (int i = 0; i < 2; i++) {
            child[i] = nullptr;
        }
    }
    ~Trie() {
        for (int i = 0; i < 2; i++) {
            if (child[i] and this != child[i]) {
                delete child[i];
            }
        }
    }
};
 
typedef Trie* pnode;
pnode root;
 
void add(int num, int val) {
    pnode curRoot = root;
    for (int i = 30; i >= 0; i--) {
        bool bit = (bool)(num >> i & 1LL);
        if (curRoot->child[bit] == nullptr) {
            curRoot->child[bit] = new Trie();
        }
        curRoot = curRoot->child[bit];
        curRoot->counter += val;
    }
}
 
int get(int num) {
    pnode curRoot = root;
    int otherNum = 0;
    for (int i = 30; i >= 0; i--) {
        bool bit = bool(num >> i & 1);
        if (curRoot->child[bit] and curRoot->child[bit]->counter > 0) {
            otherNum += bit * (1LL << i);
            curRoot = curRoot->child[bit];
        } else if (curRoot->child[bit ^ 1] and curRoot->child[bit ^ 1]->counter > 0) {
            otherNum += (bit ^ 1) * (1LL << i);
            curRoot = curRoot->child[bit ^ 1];
        } else {
            assert(false);
        }
    }
    return num + otherNum + (num | otherNum) - (num & otherNum);
}
 
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cout.precision(12);
 
    bool FILEIO = 1;
    if (FILEIO and fopen("in.txt", "r")) {
        freopen("in.txt", "r", stdin);
    }
 
    int n;
    cin >> n;
    vector<int> nums(n);
    for (int &x : nums) {
        cin >> x;
    }
    sort(nums.begin(), nums.end());
    root = new Trie();
    for (int x : nums) {
        add(x, 1);
    }
    int ans = 0;
    for (int i = n - 1; i > 0; i--) {
        add(nums[i], -1);
        int cost = get(nums[i]);
        ans |= cost;
    }
    cout << ans << endl;
}
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.