DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
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

Yet Another Hamiltonian Path Problem

Back to problem

Editorial

If A1=0A_1=0A1​=0, vertex 111 has no outgoing edge. Therefore, if a Hamiltonian path exists, vertex 111 must be the last vertex of the path.

Similarly, if AN=1A_N=1AN​=1, vertex NNN has no outgoing edge. Hence vertex NNN must also be the last vertex of any Hamiltonian path.

Therefore, when A1=0A_1=0A1​=0 and AN=1A_N=1AN​=1, two distinct vertices would both have to be the last vertex, so no Hamiltonian path exists.

In every other case, we can construct a Hamiltonian path directly.

Suppose AN=0A_N=0AN​=0. First output all vertices with Ai=1A_i=1Ai​=1 in increasing order, then output all vertices with in decreasing order. Inside the first part, the current vertex has value and the next vertex has a larger number, so the required edge always exists. Inside the second part, the current vertex has value and the next vertex has a smaller number, so the required edge always exists. If both parts are nonempty, the last vertex of the first part is smaller than , while the first vertex of the second part is . Thus the edge between the two parts also exists.

If AN=1A_N=1AN​=1, then because we are not in the impossible case, A1=1A_1=1A1​=1. Output all vertices with A in decreasing order, then all vertices with in increasing order. Edges inside each part exist for the same reason as above. If both parts are nonempty, the last vertex of the first part is greater than , while the first vertex of the second part is , so the edge between the two parts also exists.

Each vertex is processed only a constant number of times. Thus the time complexity is O(N)O(N)O(N) per test case and O(∑N)O(\sum N)O(∑N) overall. The extra space complexity is O(N)O(N)O(N).

Solution written by GPT5.6

Ai=0A_i=0
Ai​=0
111
000
NNN
NNN
i=0A_i=0
Ai​=0
Ai=1A_i=1Ai​=1
111
111