## B - Insertion Sort 2 Editorial by evima

### [1] Necessary condition

Let’s consider the invariants in the operation. (Reference material on invariants: ABC 288 - D Editorial)

Any operation can be represented by an even number of adjacent swaps. From this, we can see that the inversion number changes by an even number. In other words, the parity of the inversion number is the same before and after the operation.

Since the inversion number is \(0\) when the sequence is sorted in ascending order, we can see that the answer is `No`

if the inversion number of the given \(P\) is odd.

### [2] Construction method

In fact, if the necessary condition in [1] is satisfied, \(P\) can always be rearranged in ascending order with at most \(2000\) operations.

Repeat the following procedure until terminated:

Find the smallest \(m\) such that \(P_m\neq m\). If there is no such \(m\), then \(P\) is in ascending order, so terminate the procedure.

For \(k\) such that \(P_k=m\), if \(k < N\), perform the operation with \(i=k, j = m-1\). Otherwise, do it with \(i=N-1,j=N-3\) once, and then with \(i=k, j = m-1\).

The above procedure does not work well when \(m=N-1\), but it is impossible for \(m=N-1\) to occur due to the condition that the inversion number is even. Also, the procedure always increases \(m\) by at least \(1\) (or \(P\) becomes ascending) with one iteration, so the procedure will finish with at most \(N-2\) repetitions.

Therefore, \(P\) can be rearranged in ascending order with at most \(2000\) operations.

*(Above is a modification of a translation by GPT-4.)*

posted:

last update: