Official

A - Reverse, Recurse Editorial by evima Editorial for printing


After \(f(L,R)\) is executed, the segment \([L,R]\) is in ascending order. When the length is at least \(2\), we have \(P_L<P_R\) after the initial reversal, and the left recursive call moves the minimum value of the segment to position \(L\). The right recursive call then sorts the rest, so the claim follows by induction on the length.

First, let \(f(k)\) be the number of reversals performed when \(f(1,k)\) is executed on \((2,3,\ldots,k,1)\). The initial reversal turns the sequence into \((1,k,k-1,\ldots,2)\), and the leading \(1\) never moves afterward.

For example, when \(k=5\), the sequence after the initial reversal is \((1,5,4,3,2)\). No reversal occurs in any call that contains the leading \(1\), and the rest of the process can be summarized in the following order.

  • \(f(2,3)\) sorts \((5,4)\), making the whole sequence \((1,4,5,3,2)\).
  • \(f(2,4)\) sorts \((4,5,3)\), making the whole sequence \((1,3,4,5,2)\).
  • \(f(2,5)\) sorts \((3,4,5,2)\), making the whole sequence \((1,2,3,4,5)\).

Every one of these segments has the form “an ascending sequence with the minimum value at its end,” so the numbers of reversals in these calls are \(f(2),f(3),f(4)\), respectively. The same holds for general \(k\), so

\[ f(2)=1,\qquad f(k)=1+\sum_{i=2}^{k-1}f(i), \]

and thus \(f(k)=2^{k-2}\).

Next, consider the process on the current sequence \((q_1,\ldots,q_m)\). First, if \(q_1>q_m\), reverse the whole sequence and add \(1\) to the answer. Let \(x\) be the last value after this reversal.

The left recursive call sorts the first \(m-1\) elements. When the right recursive call is then performed, the values smaller than \(x\) do not move, so it suffices to consider only the part consisting of the values greater than \(x\) in ascending order followed by \(x\) at the end. Letting \(g\) be the number of values greater than \(x\), the number of reversals there is \(0\) if \(g=0\), and \(f(g+1)=2^{g-1}\) otherwise.

Therefore, we can add the contribution of this right recursive call to the answer up front, remove the last value \(x\), and follow only the left recursive call.

This process only reverses the whole sequence and removes the last element, so the sequence can be maintained by the positions of its two ends in the original permutation and its current direction. Also, by maintaining the number of remaining values with a BIT, we can find \(g\) at each stage. The problem can be solved in \(O(N\log N)\) time in total.

posted:
last update: