Table of Contents

ExplanationImplementation

Explanation

Let prefi\texttt{pref}_i be the xor-sum of the prefix ending at ii. We must find a previous prefix sum prefj\texttt{pref}_j such that prefiprefj\texttt{pref}_i \oplus \texttt{pref}_j is maximized.

To obtain the maximum result, the 00 bits should be flipped to 11. 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 prefj\texttt{pref}_j we'll traverse the trie trying to down the path of the opposite bit, such that after xoring with prefi\texttt{pref}_i more bits are flipped to 11.

Implementation

Time Complexity: O(NlogM)\mathcal{O}(N \cdot \log{M}), where MM 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 int
void 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!