Editorial for Baltic OI '09 P3 - Subway Signaling Error
Submitting an official solution before solving the problem yourself is a bannable offence.
One solution is to binary search for the answer. To test if it's possible to get the trains in order within time , assume that at least one train has to move exactly the distance (since a train can move both left and right, there are possibilities to try). We can now determine where all other trains must be. To check if this is possible, note that this is a bipartite matching problem where one partition consists of the train's original position, and the other partition consists of a train's final position. An edge exists between nodes in the left and right partition if the distance between the positions are at most .
Solving the max match problem with standard bipartite matching is too slow however. This can instead be accomplished much more easily by realizing that a greedy approach will work. The train with the leftmost original position can always be assigned to the leftmost of the new positions, and so on. If such an assignment is impossible (because the distance is greater than ), then no max matching exists.
The solution then involves a binary search (about iterations or so needed to get the desired precision), fixing the position of one train (), and a greedy matching (). The overall complexity is thus with a fairly large constant factor due to the binary search.
The optimal solution is more mathematical, and runs in time: First we notice that if we sort trains from left to right on the line, then the odd trains should be going in one direction and even ones in the other. That is because we are not swapping two trains in an optimal solution, and when the trains are evenly distributed, the odd ones face one direction and the even ones the other. So now we know the directions and we can only move each train to the left or right. Consider the example from the problem statement. After sorting we calculate directions:
Now it is like we were on the circle of length :
Assume that we don't move the first train. In such a situation, we easily calculate where the trains should be:
and the movements of the trains should be, respectively:
Now, if the first train moves by , all the others move by , where is the move if first train stands still. If we find minimum and maximum over the moves ( and ), when first train stands, then when it moves by , the minimum and maximum will be and . Our result would then be . This is minimized when , which gives and thus the final result is , i.e., in the example. The whole algorithm runs in .
Comments