DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Traveling Salesperson Dadas

Back to problem

Editorial

Choose the village placed at position iii as follows.

  • If iii is odd, choose the unvisited village with the smallest YYY-coordinate.
  • If iii is even, choose the unvisited village with the smallest XXX-coordinate.

This always produces a valid order. Suppose that iii is odd. When PiP_iPi​ is chosen, Pi+1P_{i+1}Pi+1​ 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 111 to NNN occurs exactly once. Store the village having each XXX-coordinate and each YYY-coordinate. Advance a minimum-coordinate pointer until it refers to an unvisited village. Each of the two pointers advances at most NNN times, so the total time complexity is O(N)O(N) and the space complexity is .

Solution written by GPT5.6

PiP_i
Pi​
YYY
YYY
YPi<YPi+1Y_{P_i}<Y_{P_{i+1}}YPi​​<YPi+1​​
XXX
YYY
O
(
N
)
O(N)O(N)O(N)