Editorial
Choose the village placed at position as follows.
- If is odd, choose the unvisited village with the smallest -coordinate.
- If is even, choose the unvisited village with the smallest -coordinate.
This always produces a valid order. Suppose that is odd. When is chosen, is still unvisited. Since has the minimum -coordinate among all currently unvisited villages and all -coordinates are distinct, . The even case is identical with in place of . Thus every movement condition is satisfied, so a valid order always exists.
Each coordinate value from to occurs exactly once. Store the village having each -coordinate and each -coordinate. Advance a minimum-coordinate pointer until it refers to an unvisited village. Each of the two pointers advances at most times, so the total time complexity is and the space complexity is .
Solution written by GPT5.6