C - Mountain and Valley Folds Editorial by evima
First, let’s observe the structure of the creases. If we extract only the odd-numbered creases, the mountain and valley folds continue as VMVM...
. If we extract only the even-numbered creases, this structure recurs. In other words, when we group the creases based on the least significant bit that is 1
in the binary representation of their indices, each group forms a sequence like VMVM...
. This can be proved using mathematical induction, among other methods. We utilize this structure in our solution.
Let \(f(a, k)\) be the answer to the problem when taking \(i\) satisfying \(i \bmod 4 = k\) for the sequence \(a = (a_1, a_2, \dots ,a_m)\).
When \(k = 0, 2\), the contribution to the answer from the odd elements of \(a\) is uniquely determined. When \(k = 1, 3\), the contribution from the even elements of \(a\) is uniquely determined. This is because, for such elements \(a_x\), the type (mountain or valley) of the fold at position \(a_x + i\) depends only on \(i \bmod 4\).
For elements whose contribution is not uniquely determined—that is, the even elements when \(k = 0, 2\), and the odd elements when \(k = 1, 3\)—we extract them and divide each by \(2\) (rounded down) to form a sequence \(b = (b_1, b_2, \dots ,b_l)\). The contribution of these elements can be counted recursively as \(\max \left( f\left( b, \left\lceil \frac{k}{2} \right\rceil \right),\ f\left( b, \left\lceil \frac{k}{2} \right\rceil + 2 \right) \right)\). This is due to the recursive structure of the creases mentioned above and the fact that \(100\) operations is sufficiently many in regard to the constraints.
The elements derived from a particular element of \(A\) appear in \(a\) at most \(\log_2 \max A\) times during recursion, so this solution is efficient enough. With appropriate implementation, the computational complexity is \(O(N \log \max A)\).
posted:
last update: