Editorial for Cheap Tricks
Submitting an official solution before solving the problem yourself is a bannable offence.
At first glance, the problem looks like a shortest-path or dynamic programming problem, since from every mark we may jump to many other marks. However, there is a much simpler way to look at the cost.
Consider the unit distance between marks and
. In any route from mark
to mark
, this unit distance must be crossed from left to right at least once. If that crossing happens during a jump whose destination is mark
, then necessarily
, and that unit of distance contributes
to the cost of the jump.
Therefore, the contribution of this unit distance is at least:
Backward jumps can only add extra positive cost, so they cannot improve this lower bound. Summing this argument over all unit distances gives:
Now we show that this lower bound can always be achieved. Suppose we are planning to jump from mark directly to mark
, but there is some mark
between them with
.
Jumping directly costs:
Going through costs:
Since , the second option is cheaper. So whenever we see a new smaller coefficient on the way to the destination, it is beneficial to land there first.
This means the optimal route uses exactly the marks that become suffix minimums. We do not need to construct the route explicitly. We scan the array from right to left, keep the minimum coefficient seen so far, and add it to the answer at every position.
For example, if:
then the suffix minimums are:
so the minimum total cost is:
Complexity
The array is scanned once from right to left, so the time complexity is:
We store the array because the input is given from left to right and we process it backwards, so the memory complexity is:
The answer can be as large as about , so a 64-bit integer type such as
long long is required.
Comments