D - Gap Swap (easy) 解説 by evima
The answer is \(\frac{1}{2} \sum |P_i-i|\).
Below, let \(f(P) = \sum |P_i-i|\).
\(P\) being in ascending order is equivalent to \(f(P) = 0\).
We show that \(\frac{1}{2} \sum |P_i-i|\) can be taken as a lower bound on the total cost.
The change in \(f(P)\) caused by the operation choosing \(i\) and \(j\) is \((|P_j-i| + |P_i-j|) - (|P_i-i|+|P_j-j|)\). By the condition of the operation, both \(P_i\) and \(P_j\) are \(\le i\) or \(\ge j\), so this change is \(0\) or \(-2(j-i)\) or \(2(j-i)\). That is, the maximum decrease per cost is \(2\), so \(\frac{1}{2} \sum |P_i-i|\) is a lower bound on the total cost required to sort \(P\) into ascending order.
We show that this lower bound is achievable.
if \(P\) is not in ascending order, it is always possible to choose \(i\) and \(j\) that change the value of \(f(P)\) by \(-2(j-i)\).
Let \(v_1,v_2,\cdots,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 \(v_i\) and \(v_{i+1}\) satisfying \(P_{v_i}>v_i\) and \(P_{v_{i+1}}<v_{i+1}\). It suffices to perform the operation choosing such \(v_i\) and \(v_{i+1}\).
From the above, the desired value is \(\frac{1}{2} \sum |P_i-i|\), which can be computed in \(O(N)\).
投稿日時:
最終更新: