B - Erase and Insert 解説 by evima
Let’s consider the permutation \(Q\) as a sequence \(A=(A_0,A_1,...,A_k)\), which represents the number of elements that have not yet been inserted between the numbers that have been placed by insertion operations. For example, in Sample 1, \(A\) becomes \((3) \rightarrow (1,1) \rightarrow (0,1,0) \rightarrow (0,0,0,0)\). Now, the \(i\)-th operation is as follows:
- Find the smallest $k$ such that $A_k$ is positive, and decrease $A_k$ by $1$. (Deletion of $i$)
- Split $A_x$ into two non-negative integers, where $x$ is the number of elements in $P$ that are less than $i$ and are located before $i$. (Insertion of $i$)
Now, if we look at the operations in reverse, they are as follows:
- Merge $A_x$ and $A_{x+1}$. (Insertion of $i$)
- Find an integer $k$ such that $A_0,A_1,\dots,A_{k-1}$ are all $0$, and increase $A_k$ by $1$. (Deletion of $i$)
We want to find the number of ways to start from \(A=(0,0,\dots,0)\) and repeat this operation \(N\) times to reach \(A=(N)\).
In the above operations, we can consider sequences with the same number of consecutive \(0\)s from the left as the same. Thus, we can perform dynamic programming with \(dp[i][j] = \) the number of ways to transform into \(A=(N)\) a sequence that, when viewed in reverse, after \(i\) operations, has \(A_0,A_1,\dots,A_{j-1} = 0\) and (if it exists) \(A_{j} \neq 0\).
The initial state is \(dp[0][N+1] = 1\). For the transition, we first determine whether \(j\) decreases by \(1\) or remains unchanged due to the merge, and then we choose \(k \le j\) to transition into. This would take \(\mathrm{O}(N^3)\) time in total, but we can speed it up to \(\mathrm{O}(N^2)\) using cumulative sums.
Therefore, the problem can be solved in a total of \(\mathrm{O}(N^2)\) time.
投稿日時:
最終更新: