Official

B - Favorite Game Editorial by evima


It can be proved that there is an optimal solution that only operates on \(A_1\) and \(A_2\).

Let’s prove it. Take an operation sequence that operates on elements other than \(A_1\) or \(A_2\). First, perform all operations on \(A_1\) and \(A_2\). At this point, it must hold that \(A_1 \le A_2\). The operation to be done on each \(i(i \ge 3)\) afterward is one of the following.

  • When $A_1 > A_i$: Either raise $A_i$ to $A_1$ or do nothing.
  • When $A_1 \le A_i \le A_2$: Do nothing.
  • When $A_i > A_2$: Either lower $A_i$ to $A_2$ or do nothing.

Here, let \(X\) be the smallest of the \(A_i\) that was lowered to \(A_1\) (if none exist, let \(X = A_1\)), and let \(Y\) be the largest of the \(A_i\) that was lowered to \(A_2\) (if none exist, let \(Y = A_2\)).

For the original operation sequence, cancel all operations done on elements other than \(A_1\) or \(A_2\), and set \(A_1\) to \(X\) and \(A_2\) to \(Y\). At this point, it can be seen that the number of integers \(i\) satisfying \(A_1 \le A_i \le A_2\) does not decrease, and the number of operations does not increase.

Therefore, it has been confirmed that operations only need to be performed on \(A_1\) and \(A_2\). From here on, let a sequence \(B\) be \((A_3, A_4, \dots, A_N)\) sorted in ascending order.

In the end, the \(i\)’s that satisfy \(A_1 \ge B_i \ge A_2\) will form an interval. Therefore, it is sufficient to brute-force the intervals of length \(M\) in \(B\), and find the minimum number of operations required for \([A_2, A_1]\) to include that interval. Therefore, by performing the above, this problem can be solved in \(\mathrm{O}(N\log N)\).

(Modified the first draft written by GPT-4.)

posted:
last update: