Official

E - Monotone OR Editorial by evima


Define \(dp[k]\), \(dp2[k]\), \(a_i\) as follows:

  • \(dp[k]\) – the number of operation sequences that finish with \(x = k\);
  • \(dp2[k]\) – the number of pairs of an operation sequence and \(i\) such that \((x | s_i) = k\);
  • \(a_i\) – the number of indices \(j\) with \(s_j = i\).

If \(a\) is precomputed, the transitions of DP are as follows:

  • \(dp[k] = dp2[k-1]\)
  • \(dp2[k] = \sum_{i | j = k} a_i dp[j] = (\sum_{i \subset k} a_i)(\sum_{j \subset k} dp[j]) - (\sum_{j \subsetneq k} dp2[j])\)

If it were possible, we would like to use the zeta transform to compute accumulated sums of \(dp\) and \(dp2\) over smaller sets, but because \(dp\) and \(dp2\) are determined sequentially, we cannot apply the zeta transform beforehand; we need to do this online somehow. Specifically, we want to solve the following problem:

We have a length-$2^N$ array $x=(x_0,x_1,\dots,x_{2^N-1})$, initially all zero. For $i = 0,1,\dots,2^N-1$ in this order, perform the following online:
  • Find $\sum_{j \subset i} x_j$, and add $v$ to $x_i$.

For each query, we must find \(\sum_{j \subset i} x_j\) fast. One approach is to maintain an array \(y\) in the following state:

  • Just before handling the query for \(i\), the following is satisfied (write \(i= 2^{b_1} + 2^{b_2} + \dots + 2^{b_k},b_1 > b_2 > \dots > b_k,c_l = \sum_{j=1}^{l} 2^{b_j}\)):
    • \((y_{c_l},y_{c_l+1},\dots,y_{c_{l+1}-1})\) equals the zeta transform of \((x_{c_l},x_{c_l+1},\dots,x_{c_{l+1}-1})\).

In this state, we have \(\sum_{j \subset i} x_i = \sum_{l = 1}^{k} y_{i\ \mathrm{xor}\ 2^{b_l}}\), so we can find \(\sum_{j \subset i} x_i\) in \(\mathrm{O}(N)\) time. To update \(y\), let \(y_i = x_i\) to append \(0\) at the end of \(b\), and then keep merging two blocks while \(b_{k-1} = b_k\). Merging can be done in linear time, so the amortized cost per update is \(\mathrm{O}(N)\).

Therefore, the problem can be solved in \(\mathrm{O}(2^N N)\) time. Be careful with memory: maintaining all \(2^N N\) intermediate values of a full zeta transform runs in \(\mathrm{O}(2^N N)\) time, but takes \(\mathrm{O}(2^N N)\) space and causes MLE.