Official

E - Increment Decrement Editorial by evima


Let us consider how we solve the problem for a fixed sequence AA.

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

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

Here, let us observe dp[i]dp[i] for a fixed ii, 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=Aians=\sum A_i.
  • Let SS be a multiset, which initially contains CC instances of 00.
  • For each ii (1iN1 \leq i \leq N), do the following:
    • Add two instances of AiA_i to SS.
    • Take out the smallest element in SS and subtract this value from ansans.
    • Delete the greatest element in SS.

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

Let us turn this into a counting problem. For each element in Bi,jB_{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 Bi,jB_{i,j} in SS. Eventually, we have a solution with the time complexity of O(N2K(M+K))O(N^2K(M+K)).

posted:
last update:



2025-03-31 (Mon)
20:44:43 +00:00