Official

C - Roughly Sorted Editorial by evima


First, for a given \(P\), let us find the minimum number of operations needed.

For each \(i\), let \(x_i\) denote the number of indices \(j\) such that \(P_j>P_i\) and \(j<i\). If there is \(i\) such that \(x_i > K\), \(P_{i-1}>P_i\) holds for the smallest such \(i\), so swapping \(P_{i-1}\) and \(P_i\) for that \(i\) reduces the inversion number.

Thus, we can find the minimum number of operations as \(\sum \max(x_i-K,0)\).

By the way, doing the minimum number of swaps will result in a unique \(P\). We can see this by considering, for each \(v=N,N-1,\cdots,1\), the relative position of \(v\) among the values not less than \(v\).

Let us solve the original problem. For each \(v=N,N-1,\cdots,1\), consider the relative position of \(v\) in \(P\) among the values not less than \(v\). Let \(y_v\) be the number of values in \(P\) that appear earlier than \(v\) and are greater than \(v\). Then, we can see that if \(y_v<K\), the relative position of \(v\) is fixed. On the other hand, if \(y_v=K\), it can be anywhere as long as it is to the right of, or the same as, its eventual position in \(P'\).

Thus, the answer is the product of the numbers of candidates for every \(v\).

The complexity of this solution is \(O(N^2)\) or \(O(N\log N)\).

posted:
last update: