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

double eulerian circuit

Back to problem

Editorial

Existence

A vertex of degree 111 forces an immediate traversal back along the same edge, so no solution exists. Conversely, minimum degree at least 222 is sufficient. Bridges do not prevent a solution.

Construction

Duplicate every edge and find an Euler circuit with Hierholzer's algorithm. Each original edge is now traversed twice. Call two consecutive uses of the same original edge a U-turn, including the junction between the last and first edges.

Choose a U-turn u→v→uu\to v\to uu→v→u. Since vvv has degree at least 222, the circuit has another visit x→v→yx\to v\to yx→v→y. Both uses of edge uvuvuv are already in the chosen U-turn, so x≠ux\neq ux=u and y≠uy\neq uy=u. It is possible that x=yx=yx=y.

Reverse the segment v→u→⋯→x→vv\to u\to\cdots\to x\to vv→u→⋯→x→v between the two visits. The two junctions become u→v→xu\to v\to xu→v→x and , neither of which is a U-turn. Inside the reversed segment, only the direction changes, so U-turn status is unchanged. The walk remains closed and every edge keeps its traversal count. Thus at least one U-turn disappears and none is created.

Initially there are at most MMM U-turns, since each one uses both copies of a different original edge. Finding a U-turn, finding another visit, and reversing the segment each take O(M)O(M)O(M) time. Total time is O(N+M2)O(N+M^2)O(N+M2) and space is . Across test cases, time is at most . Connectivity gives .

Subtasks

For subtask 1, use a ternary mask to store each edge's usage count in {0,1,2}\{0,1,2\}{0,1,2}. Fix the first input edge as the first traversal in one direction. Any valid circuit can be rotated and, if needed, reversed to satisfy this choice. Memoize failed states consisting of the current vertex, previous edge, and ternary mask. Time is O(NM23M)O(NM^2 3^M)O(NM23M) and space is . The bounds and make this feasible.

For subtask 2, a connected graph of maximum degree at most 222 is a path or a cycle. A path is impossible; traverse a cycle twice in the same direction. Time and space are O(N+M)O(N+M)O(N+M).

Subtask 3 uses the U-turn removal algorithm above.

Solution written by GPT

u→v→yu\to v\to y
u→v→y
O(N+M)O(N+M)
O(N+M)
O(∑N+(∑M)2)O(\sum N+(\sum M)^2)O(∑N+(∑M)2)
N≤M+1N\leq M+1N≤M+1
O(NM3M)O(NM3^M)
O(NM3M)
M≤6M\leq6M≤6
∑M≤200\sum M\leq200∑M≤200