Official

C - Swaps 2 Editorial by evima


Let \(A'_i = A_i + i\). Then, the operation swaps \(A'_i\) and \(A'_{i + 1}\).
Thus, we now want to solve the following problem after setting \(A_i \leftarrow A_i + i, B_i \leftarrow B_i + i\):
Determine whether it is possible to make \(A = B\) by repeatedly swapping \(A_i\) and \(A_{i + 1}\) for a chosen \(i\). If it is possible, find the minimum number of operations needed.

If \(A\) and \(B\) are not equal as sets, it is impossible to make \(A = B\).
Otherwise, if we decide a sequence \(s\) such that we will eventually bring \(A_i\) to \(B_{s_i}\), the minimum number of operations needed to realize it is the inversion number of \(s\), which we can find in \(O(N \log(N))\) time.
The problem is that \(s\) is not uniquely determined since \(A\) and \(B\) may contain duplicates, but it turns out that we can find the optimal \(s\) as follows:

  • Assume that the same value \(c\) appears as \(A_{i_1}, A_{i_2}, A_{i_3}, \dots, A_{i_n} (i_1 < i_2 < i_3 < \dots < i_n)\) and \(B_{j_1}, B_{j_2}, B_{j_3}, \dots, B_{j_n} (j_1 < j_2 < j_3 < \dots < j_n)\).
  • We can freely rearrange \(s_{i_1}, s_{i_2}, s_{i_3}, \dots, s_{i_n}\). However, swapping \(s_i\) and \(s_j\) when \(i < j\) and \(s_i > s_j\) decreases the inversion number, so \(s_{i_k} = j_k\) obtained by repeating such an operation is optimal.

posted:
last update: