Official

B - Pass on Path Editorial by evima


Let us name the two travelers A and B.

Before they visit both ends of the road and return to the starting point, they must pass each other twice. In one of those moments, A should be facing east, and in the other, A should be facing west. At that moment, when A is facing west, let \(l\) be the distance from the rest area where they are to the west end of the road. Here, the “gap” from A to B is \(2l\). Similarly, at the moment they pass each other when A is facing east, if \(r\) is the distance from the rest area where they are to the east end of the road, the gap from A to B is \(2r\).

If these two gaps are different, one of the travelers must wait (or adjust the speed, etc.) while the other covers the difference, which takes extra time. Thus, the shortest time needed for the round trip is:

\(2L + 2|l-r|\).

Moreover, both travelers can actually finish the round trip in this time. Specifically, they can start in opposite directions at one of the rest areas where they pass each other, and wait only at the other rest area to adjust the timing (at all other times, they move at a speed of \(1\)).

Therefore, one should choose the rest areas where they pass each other to minimize the difference between \(r\) and \(l\), which can be done fast enough using two pointers or sorting.

posted:
last update: