Official

E - Increment Decrement Editorial by evima


Let us consider how we solve the problem for a fixed sequence \(A\).

Assume we obtain \(p_1,p_2,\cdots,p_N\) by using just Operation \(2\). Let us consider the minimum cost needed here. First, for each \(i\) (\(1 \leq i \leq N\)), the cost of \(|A_i-p_i|\) will be incurred. Then, let us consider the cost needed to make the sequence \(p\) using just Operation \(2\). By focusing on the change in the difference between adjacent elements, we can see this cost is \(M \times \sum_{i=0}^N |p_i - p_{i+1}|/2\), where \(p_0=p_{N+1}=0\). We can rewrite the above formula as \(M \times \sum_{i=0}^N \max(p_{i+1}-p_i,0)\). Now, the problem is to set \(p_i\) to minimize the total cost above.

To solve this naively with DP, we can consider the following: \(dp[i][j]=(\)the minimum cost when the first \(i\) elements have been set and \(p_i=j)\).

Here, let us observe \(dp[i]\) for a fixed \(i\), and it forms a convex polyline. Then, let us think of maintaining the set of points where the angle of the polyline changes, and the problem boils down to the following simple greedy strategy:

  • Initialize \(ans=\sum A_i\).
  • Let \(S\) be a multiset, which initially contains \(C\) instances of \(0\).
  • For each \(i\) (\(1 \leq i \leq N\)), do the following:
    • Add two instances of \(A_i\) to \(S\).
    • Take out the smallest element in \(S\) and subtract this value from \(ans\).
    • Delete the greatest element in \(S\).

(By the way, this is the intended solution for the original problem.)

Let us turn this into a counting problem. For each element in \(B_{i,j}\), we want to find the number of times it is used. We can find it with DP where the state is the number of instances smaller than \(B_{i,j}\) in \(S\). Eventually, we have a solution with the time complexity of \(O(N^2K(M+K))\).

posted:
last update: