G - Partial Xor Enumeration Editorial by spheniscine


This problem is an application of a technique called “XOR basis”, as described in this Codeforces blogpost. In fact, “problem 4” in that blogpost is quite similar to this problem.

In summary, you treat \(A\) as a matrix with elements in \(\mathbb Z _2\) (the values \(0\) and \(1\) with addition done modulo \(2\)), with \(N\) rows and \(60\) columns. You wish to reduce this matrix to a new matrix with the same number of columns but as few rows as possible, such that the set of possible xor-sums of subsequences (\(s\)) remains the same.

First, you have a matrix \(B\) with \(60\) rows and columns, all zeros, and you want to maintain the following invariants:

  • Each row of \(B\) is either zero or a “basis vector” from the set of possible sums.
  • If the \(k\)-th row of \(B\) is non-zero, the highest one-bit should be the \(k\)-th bit.

So for each row of \(A\), repeat the following procedure:

  • if \(A_i\) is zero, terminate
  • Otherwise find the highest one-bit in \(A_i\). Let its index be \(j\).
  • If \(B_j\) is zero, \(B_j \larr A_i\).
  • Otherwise, do \(A_i \larr A_i \oplus B_j\), and continue.

Then remove all zero rows from \(B\). The number of rows left in it is the rank of \(A\) (and also the rank of \(B\)), and each row in \(B\) is a basis vector. If the rank is \(m\), there are exactly \(2^m\) values in sequence \(s\).

To produce the answer, we describe the procedure for obtaining the \(i\)-th element of \(s\):

  • First, make \(i\) zero-indexed. Now \(i < 2^m\).
  • let \(ans\) be a zero-vector.
  • read the bits of \(i\) from high to low, these correspond to the rows of \(B\) from high to low. If the bit is \(1\), \(ans \larr \max(ans, ans \oplus B_j)\), otherwise \(ans \larr \min(ans, ans \oplus B_j)\).
  • \(ans\), when interpreted as a binary number, is the result.

Final time complexity: \(O((N + (R - L)) \log A_{\max})\)

posted:
last update: