A - Operations on a Stack Editorial by evima
For an ascending sequence of integers \(1 \leq p_1 \lt p_2 \lt \cdots \lt p_l \leq N\), a necessary and sufficient condition for the existence of an operation sequence such that the elements remaining in the stack at the end are the \(p_1\)-th, \(p_2\)-th, \(\ldots\), \(p_l\)-th elements of \(A\) is:
\(p_i - p_{i-1}\) is odd for all \(i = 1, 2, \ldots, l+1\),
where \(p_0 \coloneqq 0\) and \(p_{l+1} \coloneqq N+1\).
- (Necessity) For the \(p_i\)-th element to remain in the stack after the \(p_{i-1}\)-th element, the operations for the \((p_{i-1}+1)\)-th through the \((p_i-1)\)-th must be done in such a way that those elements do not remain in the stack. Therefore, among those operations from the \((p_{i-1}+1)\)-th to \((p_i-1)\)-th, the number of push operations must equal the number of pop operations. Hence, \(p_i - p_{i-1}\) must be odd.
- (Sufficiency) For each \(i\), during the operations from the \((p_{i-1}+1)\)-th through \((p_i-1)\)-th, one can push and pop alternately in matching numbers, and then push on the \(p_i\)-th operation, so that the desired element remains in the stack.
Therefore, the problem is equivalent to choosing whether each element of \(A\) remains in the stack (conveniently regarding the \(0\)-th and \((N+1)\)-th elements as also remaining) so that the difference between adjacent indices of the remaining elements is odd, and maximizing the sum of the remaining elements.
We can solve this by dynamic programming in \(O(N)\) time, deciding in order for \(i = 1, 2, \ldots, N\) whether to keep the \(i\)-th element in the stack or not. Define the DP table:
\(\mathrm{dp}[i][j] =\) (the maximum possible sum of kept elements among the decisions whether to keep elements up to the \(i\)-th, assuming the most recently kept element was an even number of steps earlier if \(j = 0\), and an odd number of steps earlier if \(j = 1\)).
Using this DP approach, we can solve the problem in \(O(N)\) time.
posted:
last update: