Official

E - Swap Places Editorial by en_translator


First of all, the first key to solve the problem is that there are fairly small number of states as a result of operations. Specifically, a state is determined by “which of vertices \(1\)-\(N\) is Takahashi at?” and “which of vertices \(1\)-\(N\) is Aoki at?”, whose number is bounded by \(N \times N \leq 4 \times 10^6\).
In such a problem with sufficiently few states, we can use the approach of finding the shortest-path algorithm to find the minimum number of operations. Let \(G'\) be the graph whose vertices are the states and whose edges \(u \to v\) exist if the transition from state \(u\) to state \(v\) is possible. Then, the minimum number of operations required coincides with the length of the shortest path on \(G'\) from the vertex that corresponds to the initial state to the final. Thus, the answer can be found with BFS (Breadth-First Search) in an \(\mathrm{O}(\text{the number of vertices} + \text{edges of }G')\).

  • The observation so far is similar to the similar past problems like ABC235 D and ABC272 D. Use these problem for understanding and exercise.

Another key is the complexity analysis. We will show that, while the number of vertices is \(N^2\) as already mentioned, the number of edges is bounded by \(4M^2\).
Let \(G\) be the graph given in the graph. Let \(g_n\) be the sequence of vertices that is adjacent to vertex \(n\) on \(G\).
Suppose that Takahashi is at \(u\) and Aoki at \(v\). Then, the possible next state is “Takahashi is at a vertex adjacent to \(u\) and Aoki a vertex adjacent to \(v\).” (In fact, there is a constraint on the vertex colors, so only some of the transitions is actually valid.)

Therefore, the following equation on \(g_u\) and the number of edges \(M\) in \(G'\):

\[ \begin{aligned} M' &\leq \sum_{u=1}^N \sum_{v=1}^N \sum_{x \in g_u} \sum_{y \in g_v} 1 \\ &=\sum_{u=1}^N \sum_{v=1}^N \left(|g_u| |g_v|\right). \end{aligned} \]

We deform the right hand side. Since \(|g_u|\) equals \(\deg(u)\), the degree of vertex \(u\) on \(G\), so

\[ \begin{aligned} &=\sum_{u=1}^N \sum_{v=1}^N \left(\deg(u) \deg(v) \right); \end{aligned} \]

by reording the sigmas in the double sum,

\[ \begin{aligned} &=\left(\sum_{u=1}^N \deg(u) \right) \left(\sum_{v=1}^N \deg(v) \right)\\ &=\left(\sum_{u=1}^N \deg(u) \right)^2; \end{aligned} \]

then, since \(\sum_{u=1}^N \deg(u) = 2M\) (by the handshake lemma),

\[= 4M^2.\]

Therefore, we can assert that \(M' \leq 4M^2\). Hence, the BFS works in a total of \(\mathrm{O}(N^2 + M^2)\) time, which is fast enough. (Actually, the number of valid states is bounded by \(N^2/4\), so the constant factor is small)

Bonus (maybe for advanced readers): by the property of the BFS, the maximum answer is the number of vertices in \(G'\), i.e. in the order of \(N^2\). Now, construct a graph whose answer is \(\mathrm{\Theta}(N^2)\).

posted:
last update: