Explanation
Let be the xor-sum of the prefix ending at . We must find a previous prefix sum such that is maximized.
To obtain the maximum result, the bits should be flipped to . Now, we can use a trie to maintain the binary representations of the xor-sums of prefixes. We add the values in the trie from the most significant to the least significant bit.
When querying for we'll traverse the trie trying to down the path of the opposite bit, such that after xoring with more bits are flipped to .
Implementation
Time Complexity: , where is the maximum value
C++
#include <bits/stdc++.h>using namespace std;const int MAX_N = 2e5;int node_count;int trie[32 * MAX_N][2]; // 32 bits in an intvoid insert(int val) {int node = 0;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!