Cod sursa(job #2624753)

Utilizator CosminMorarMorar Cosmin Andrei CosminMorar Data 5 iunie 2020 11:48:15
Problema Xor Max Scor 55
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.99 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("xormax.in");
ofstream fout("xormax.out");
int n, max_value, nr_max_biti, sol_value = -1, sol_left, sol_right;
int v[100100], xorpart[100100];

struct trie {
    trie *bit[2];
    int last_poz;

    trie() {
        bit[0] = bit[1] = nullptr;
    }
};

int nr_biti(int x) {
    int cnt = 0;
    while (x) {
        cnt++;
        x >>= 1;
    }
    return max(1, cnt);
}

void add(trie *nod, int x, int nr_bit, int p) {
    if (nr_bit == 0) {
        nod->last_poz = p;
        return;
    }

    for (int i = 0; i <= 1; i++)
        if (((x & (1 << (nr_bit - 1))) > 0) == (bool)i) {
            if (nod->bit[i] == nullptr)
                nod->bit[i] = new trie();
            add(nod->bit[i], x, nr_bit - 1, p);
        }
}

int find_poz(trie *nod, int nr_bit, int want) {
    if (nr_bit == 0)
        return nod->last_poz;

    bool want_bit = (bool)((want & (1 << (nr_bit - 1))) > 0);

    if (nod->bit[want_bit] == nullptr)
        return find_poz(nod->bit[!want_bit], nr_bit - 1, want);
    return find_poz(nod->bit[want_bit], nr_bit - 1, want);
}

int main() {
    fin >> n;
    for (int i = 1; i <= n; i++) {
        fin >> v[i];
        xorpart[i] = xorpart[i - 1] ^ v[i];
        max_value = max(max_value, v[i]);
    }

    nr_max_biti = nr_biti(max_value);

    trie *root = new trie();
    add(root, 0, nr_max_biti, 0);

    for (int i = 1; i <= n; i++) {
        /// cautam secventa care se termina in i si are xor maxim
        int poz = find_poz(root, nr_max_biti, (xorpart[i] ^ ((1 << nr_max_biti) - 1)));

        int xor_secv = xorpart[i] ^ xorpart[poz];
        if (xor_secv > sol_value) {
            sol_value = xor_secv;
            sol_left = poz + 1;
            sol_right = i;
        }

        /// adaugam in trie inca un numar
        add(root, xorpart[i], nr_max_biti, i);
    }

    fout << sol_value << ' ' << sol_left << ' ' << sol_right << '\n';
    return 0;
}