F - Erase and Raise Editorial by evima
First, let us consider, for a fixed final sequence \(B_1, B_2, \cdots, B_M\), whether it can be constructed.
Clearly, the following conditions are necessary:
- \(M = N \pmod 2\)
- All the \(B_i\) are distinct.
In addition,
- \(M + \Sigma_{i=0}^{M}{|B_i - B_{i+1}|} \le N\)
is necessary, where \(B_0 = B_{M + 1} = 0\). This can be shown from the fact that the left-hand side never increases as a result of an operation.
And in fact, these turn out to be a necessary and sufficient condition. If they are satisfied, then by repeatedly applying to \(B\) the operation “insert two \(0\)s, and subtract \(1\) from all values between them,” we can obtain a sequence of length at most \(N\) all of whose elements are \(0\). Viewing this operation in reverse gives a sequence of operations that constructs \(B\) from \(A\).
It remains to count the number of \(B\) satisfying these conditions. To handle the constraint that all \(B_i\) are distinct, consider a DP that inserts values into \(B\) in increasing order. That is, starting from an empty array, we build \(B\) by repeating the steps: insert at most one copy of \(0\) → insert at most one copy of \(1\) → … and so on.
Indeed, \(\Sigma_{i=0}^{M}{|B_i - B_{i+1}|}\) is also well-suited to this construction method, because this value is equal to “the total number of positions, over all values \(x\), where an element at most \(x\) is adjacent to an element at least \(x + 1\).”
Specifically, the information we need to maintain is “among the \(|B| + 1\) gaps (including the two ends) between elements, the number of gaps into which one or more elements will be inserted in the future.” This is because this count corresponds to the “number of positions where an element at most \(x\) is adjacent to an element at least \(x + 1\)” mentioned above. By maintaining this, \(M + \Sigma_{i=0}^{M}{|B_i - B_{i+1}|}\) can be computed incrementally (for \(M\), it suffices to increment it by \(1\) each time an element is added).
This gives an \(O(N^2)\)-time DP that maintains the following information. In particular, it turns out that “the value being considered for the next addition” does not need to be kept as part of the state.
- Among the \(|B| + 1\) gaps (including the two ends) between elements, the number of gaps into which one or more elements will be inserted in the future.
- The current value of \(M + \Sigma_{i=0}^{M}{|B_i - B_{i+1}|}\).
Finally, combining the facts that the former value increases by at most \(1\) at a time, and that the latter value is at least the cumulative sum of the former value up to that point, we can see that the former value is in fact at most \(O(\sqrt {N})\). Therefore, this DP runs in \(O(N \sqrt{N})\) time.
posted:
last update: