Editorial for COCI '20 Contest 5 #2 Po
Submitting an official solution before solving the problem yourself is a bannable offence.
The problem is equivalent to starting from the given sequence and reaching all zeros in the minimum number of decreasing steps.
The main insight is that if we take a number to zero using only one decrease, we should also take all other elements equal to in the same step, unless there are elements less than in between them. For example, take the sequence . If we take any to zero in a single step, we should decrease the segment spanning all of them.
It is also clear that the minimal nonzero element of the sequence should be taken to zero in a single decrease. This gives us a solution for ; just keep track of the minimal nonzero value, and always decrease some minimal elements.
We can make this approach fast using a segment tree, but the intended solution is simpler.
Traverse the sequence from left to right. It can be proven that each element contributes step to the optimal solution, except those elements for which there is an element of equal value to the left, and there are no smaller elements between them.
We can efficiently find whether each element satisfies the above condition using a monotone stack. We push values to the top of the stack after popping the stack until the new element is not smaller than the old top of the stack. If the top and the new element have equal values, we don't add to the solution. The complexity is .
Comments