C - Balls and Boxes 解説 by evima
Consider the directed graph \(G_P\) formed by drawing a directed edge from each box \(i\) to box \(P_i\). Similarly, consider \(G_Q\) formed by drawing a directed edge from each box \(i\) to box \(Q_i\).
Since \(P\) and \(Q\) are permutations, each connected component of \(G_P\) and \(G_Q\) is a cycle. Let \(C_P\) be the cycle in \(G_P\) containing \(X\), and \(C_Q\) the cycle in \(G_Q\) containing \(X\). If there is a red ball outside \(C_P\), it can never reach \(X\), so the answer is \(-1\). The same goes if there is a blue ball outside \(C_Q\). We now focus on the other cases.
To move all red balls to \(X\), consider the red ball \(\rho\) that is the farthest along the cycle \(C_P\) from \(X\) (that is, the one that would take the greatest number of steps to reach \(X\) following the directed edges). We only need to focus on moving \(\rho\) to \(X\). This is because, in the process of moving \(\rho\), any other red balls on the path are naturally transferred to \(X\) as well. The same logic applies to blue balls.
Therefore, we only need to consider the following situation:
- Only box \(a_1\) contains red balls, and there is a path from \(a_1\) to \(X\) in \(G_P\): \(a_1 \to a_2 \to \cdots \to a_{|A|} \to X\).
- Only box \(a_1\) contains blue balls, and there is a path from \(b_1\) to \(X\) in \(G_Q\): \(a_1 \to a_2 \to \cdots \to b_{|B|} \to X\).
Both balls will be in box \(X\) after performing the operation on boxes \(I_1, I_2, \ldots, I_{|I|}\) in this order if and only if the sequence of operations \(I = (I_1, I_2, \ldots, I_{|I|})\) contains both \(A = (a_1, a_2, \dots, a_{|A|})\) and \(B = (b_1, b_2, \dots, b_{|B|})\) as not necessarily contiguous subsequences (and does not contain \(X\)). The shortest such sequence has length \(|A| + |B| - L\), where \(L\) is the length of the Longest Common Subsequence (LCS) of \(A\) and \(B\).
To find the LCS of A and B, renumber the \(N\) boxes \(1, 2, \ldots, N\) so that \(A = (1, 2, \ldots, |A|)\) (and modify \(b_1, b_2, \ldots, b_{|B|}\) accordingly), and the LCS can be found as the Longest Increasing Subsequence (LIS) of \(B\) in \(O(N \log N)\) time.
投稿日時:
最終更新: