Official

F - Construct a Palindrome Editorial by en_translator


Imagine: there is a piece on each of vertex \(1\) and \(N\), and you repeat the following: “move each piece to its adjacent vertex, using the edges with the same character written on them” — so that two pieces eventually come close.
For a palindrome of even length, it is sufficient to find the minimum number of such moves until the two pieces reaches to the same vertex; for a palindrome of odd length, it is enough to find the minimum number of such moves until the distance between the two pieces becomes exactly one.
In order to calculate this, let us consider a graph with \(N^2\) vertices, each of which correspond to every pair \((a, b)\) of vertices in the original graph. There is a edge from the vertex corresponding to \((a, b)\) to that of \((c, d)\) if and only if there are edges between \(a\) and \(c\), and \(b\) and \(d\), in the original graph, and the characters on these edges are the same.
The number of edges is in total \(O(\sum_a \sum_b (\mathrm{deg}(a)\mathrm{deg}(b))) = O(\sum_a (\mathrm{deg}(a) M)) = O(M^2)\), so we can easily explicitly construct the graph.
All that left is perform a breadth-first search (BFS) on this graph starting from the vertex corresponding to \((1, N)\), and check for the palindromes of even and odd lengths. (For the even-length ones, it is sufficient to check the shortest distance to the vertex corresponding to \((i, i)\) for all \(i\); for the odd-length ones, it is enough to check the shortest distances to the vertices corresponding to \((a, b)\) and that of \((b, a)\), for all edges \((a, b)\))

posted:
last update: