Official

C - 1 Loop Bubble Sort Editorial by evima


Consider the problem when \(Q\) is fixed.

If \(Q_N \neq N\), the answer is clearly \(0\). If \(Q_N = N\), the answer can be proved to be \(2^k\), where \(k\) is the number of \(i\) (\(2 \leq i \leq N\)) such that \(Q_i = \max(P_1, \ldots, P_i)\), by focusing on the pre-operation position of \(Q_N\) and using mathematical induction on \(N\).

Now consider the case where \(Q\) varies. When we decide \(Q\) from the first term onward, if we multiply by \(2\) each time the maximum value is updated, then the only information we need is the maximum value of \(Q\) decided so far.

Define this dynamic programming table: dp[Number of terms \(i\) determined in the beginning][\(\max(Q_1,\ldots,Q_i)=j\)] = Total count

This solves the problem in \(\mathrm{O}(N^3)\). This dynamic programming can be optimized to \(\mathrm{O}(N^2)\) using prefix sums.

posted:
last update: