E - Gap Swap (hard) Editorial by evima
Let \(\text{inv}(P)\) be the number of inversions of \(P\), and let \(\text{sum}(P)=\sum_{i=1}^{N}|i-P_i|\). The answer is \(\text{sum}(P)-\text{inv}(P)\). We show this below.
Below, let \(f(P)=\text{sum}(P)-\text{inv}(P)\).
First, \(f(P)\) does not change if we remove an element with \(P_r=r\), decrease by \(1\) each position and value greater than \(r\), and reinterpret the result as a permutation of \((1,2,\ldots,N-1)\). For elements that straddled the removed fixed point, \(|i-P_i|\) decreases by \(1\), and the inversion with that fixed point also disappears, decreasing the count by \(1\). Everything else stays unchanged, so the decreases in \(\text{sum}(P)\) and \(\text{inv}(P)\) match.
We show that \(f(P)\) is a lower bound on the total cost.
If we remove the fixed points lying between the two chosen points in an operation, that operation can be regarded as an adjacent swap. When adjacent elements \(a=P_i\) and \(b=P_{i+1}\) are swapped, the change in \(\text{sum}(P)\) is one of \(-2,0,2\), and the number of inversions increases by \(1\) if \(a<b\) and decreases by \(1\) if \(a>b\). \(\text{sum}(P)\) decreases by \(2\) only if \(a>i\) and \(b<i+1\), in which case \(a>b\) always holds, so the number of inversions also decreases by \(1\). Therefore, a single operation decreases \(f(P)\) by at most \(1\). Since \(f(P)=0\) when \(P\) is in ascending order, the required total cost is at least \(f(P)\).
The same holds even if positions with \(P_i=i\) can also be chosen as targets of the operation. Above we removed fixed points, but even if the removed fixed points are kept and used as targets of the operation, the same argument shows that \(f(P)\) cannot be decreased by \(2\) or more in one operation.
We show that the lower bound shown above is achievable.
When \(P\) is not in ascending order, there always exists an operation that decreases \(f(P)\) by exactly \(1\). Let \(v_1,v_2,\ldots,v_t\) be the values of \(k\) satisfying \(P_k\neq k\), in increasing order. Since \(P_{v_1}>v_1\) and \(P_{v_t}<v_t\), there must exist adjacent \(v_i\) and \(v_{i+1}\) satisfying \(P_{v_i}>v_i\) and \(P_{v_{i+1}}<v_{i+1}\).
Since all elements between this \(v_i\) and \(v_{i+1}\) are fixed points, the operation choosing these two points is possible. If we remove the fixed points, this is an adjacent swap satisfying \(P_i>i\) and \(P_{i+1}<i+1\). Thus, \(\text{sum}(P)\) decreases by \(2\) and the number of inversions decreases by \(1\), so \(f(P)\) decreases by exactly \(1\).
By repeating this, \(P\) can be sorted into ascending order in \(f(P)\) operations. Therefore, the minimum cost is \(f(P)=\text{sum}(P)-\text{inv}(P)\).
We now need to find \(\text{sum}(P)\) and \(\text{inv}(P)\) in the initial state. \(\text{sum}(P)\) can be found in \(O(N)\), and \(\text{inv}(P)\) can be found in \(O(N\log N)\) using Fenwick Tree, etc.
The overall time complexity is \(O(N\log N)\).
posted:
last update: