Official

D - Binary Representations and Queries Editorial by evima


If the \(i\)-th and \((i+1)\)-th queries satisfy \(X_i \neq X_{i+1}\), swapping these two queries does not change the final answer.

To verify this, we first assume \(X_i = 0, X_{i+1} = 1\) and \(Y_i = 0, Y_{i+1} = 0\) without loss of generality. Additionally, in these two queries, additions within the four elements \(A_{4k}\), \(A_{4k+1}\), \(A_{4k+2}\), and \(A_{4k+3}\) are performed for \(k = 0, 1, 2, \ldots, 2^{N-2}-1\) “in parallel,” so it is enough to verify for just \(k = 0\) as a representative. Then, one can actually perform the operations for \((A_0, A_1, A_2, A_3)\) to verify that the result does not depend on the order of the two queries.

Therefore, we may rearrange the queries without changing the relative order of queries with equal \(X_i\) so that:

  • first, only the queries with \(X_i = 0\) are executed;
  • next, only the queries with \(X_i = 1\) are executed;
  • next, only the queries with \(X_i = 2\) are executed;
  • \(\cdots\)
  • finally, only the queries with \(X_i = N-1\) are executed.

Thus, it is enough to solve the case where all queries have the same \(X_i\) fast enough.

We assume \(X_1 = X_2 = \cdots = X_Q = 0\) without loss of generality. Additionally, let \(A^{(i)} = (A^{(i)}_0, A^{(i)}_1, \ldots, A^{(i)}_{2^N-1})\) denote \(A\) just after executing up to the \(i\)-th query.

If we let:

\[ \mathbf{M}_0 := \left[\begin{matrix} 1 & 0 \\ 1 & 1\\ \end{matrix}\right], \,\,\, \mathbf{M}_1 := \left[\begin{matrix} 1 & 1 \\ 0 & 1\\ \end{matrix}\right], \]

then for any \(k = 0, 1, 2, \ldots, 2^{N-1}\),

\[ \left[\begin{matrix} A^{(i)}_{2k}\\ A^{(i)}_{2k+1}\\ \end{matrix}\right] = \mathbf{M}_{Y_i} \left[\begin{matrix} A^{(i-1)}_{2k}\\ A^{(i-1)}_{2k+1}\\ \end{matrix}\right], \]

so for any \(k = 0, 1, 2, \ldots, 2^{N-1}\),

\[ \left[\begin{matrix} A^{(Q)}_{2k}\\ A^{(Q)}_{2k+1}\\ \end{matrix}\right] = \mathbf{M}_{Y_Q}\mathbf{M}_{Y_{Q-1}}\ldots \mathbf{M}_{Y_1} \left[\begin{matrix} A^{(0)}_{2k}\\ A^{(0)}_{2k+1}\\ \end{matrix}\right]. \]

Therefore, by computing the product of the \(Q\) matrices \(\mathbf{M}_{Y_Q}\mathbf{M}_{Y_{Q-1}}\ldots \mathbf{M}_{Y_1}\) once, one can use it to compute every element of \(A^{(Q)}\) in \(\mathrm{O}(1)\) time per element.

posted:
last update: