Official

D - Moving Pieces on Line Editorial by evima


First, since the vertices lie in a wide enough region, we can rephrase the maroon’s objective as making \(\{t_1, t_2, \cdots, t_K\}\) the set of points with two incident edges in different colors.

Let us sort the initial positions of the pieces beforehand. Let \(b_1, b_2, \cdots, b_N\) be the final positions of the \(N\) pieces. Then, the combination of colors of edges does not depend on the paths of the pieces but only depends on the positional position between \(a_i\) and \(b_i\). Thus, for a fixed set of final positions, the minimum number of operations needed is \(\sum_{i=1}^n |a_i - b_i|\). Here, we can obviously assume \(b_1 \leq b_2 \leq \cdots \leq b_N\).

Now, what type of \(b\) achieves the desired combination of colors? Consider adding \(a_i\) and \(b_i\) into a multiset \(S\), and let \(T\) be the set of numbers occurring an odd number of times in \(S\). If the set of points with two incident edges in different colors equal \(T\), such \(b\) achieves the objective.

That is, we can consider everything \(\mod 2\). From \(a\) and \(t\), the set of numbers occurring an odd number of times in \(b\) is uniquely determined (let it be \(\{c_1 < c_2 < \cdots < c_l\}\)), and we can freely let numbers occur an even number of times in \(b\). If the size of this set of numbers occurring an odd number of times is greater than \(N\), the objective is unachievable.

Let us minimize the cost. We choose some elements in \(a\) and make them correspond to those in \(c\). For the other elements, we should pair the two leftmost ones by moving them to the same position, pair the next two elements, and so on. (Since \(K\) is even, we do not have to care about the parity of the number of elements.)

From those observations, by letting dp[\(i\)][\(j\)][\(f\)] be the smallest total cost when \(a_1, \cdots, a_i\) are handled, \(c_1, \cdots, c_j\) are tied, and \(f\) elements in \(a\) are waiting in an incomplete pair, we can compute the answer in \(\mathrm{O}(N(N+K))\) time. (We can also do it without maintaining \(f\), because if there are tied elements between a pair, we can shift that pair.)

posted:
last update: