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

3-Edge

Back to problem

Editorial

A valid graph exists if and only if VVV is even and at least 444. If this condition is not satisfied, output -1.

Otherwise, first connect the vertices in a cycle in numerical order. Add the edge (i,i+1)(i,i+1)(i,i+1) for each 1≤i<V1 \leq i < V1≤i<V, and add the edge (V,1)(V,1)(V,1). Then add the edge (i,i+V/2)(i,i+V/2)(i,i+V/2) for each 1≤i≤V/21 \leq i \leq V/21≤i≤V/2.

The total number of edges added is V+V/2=3V/2V+V/2=3V/2V+V/2=3V/2. Output this number first, then output each edge directly in the order described above.

When a graph can be constructed, the time complexity is O(V)O(V)O(V). The auxiliary space complexity is O(1)O(1)O(1) because the edges can be output without storing them. An impossible case takes O(1)O(1)O(1) time.

Proof

If every vertex has degree 333, the sum of all vertex degrees is 3V3V3V. Each edge contributes 111 to the degree of each of its two endpoints, so the degree sum is twice the number of edges. Therefore, 3V3V3V is even, which means that VVV must be even.

Since self-loops and duplicate edges are forbidden, each vertex must be connected to three distinct other vertices. Thus, is also necessary.

Solution written by GPT6

V≥4V\geq 4
V≥4

Now suppose that VVV is even and at least 444. The cycle connects each vertex to two distinct neighbors. The added edges (i,i+V/2)(i,i+V/2)(i,i+V/2) use every vertex as an endpoint exactly once, giving each vertex one additional incident edge.

Each added edge connects two distinct vertices. Since 2≤V/2≤V−22 \leq V/2 \leq V-22≤V/2≤V−2, opposite vertices on the cycle are not adjacent. Thus, none of the added edges duplicates a cycle edge. The added edges share no endpoints with one another, so they do not duplicate one another either.

The resulting graph therefore has no self-loops or duplicate edges, and every vertex has degree exactly 333. Such a graph can always be constructed when the necessary conditions hold, proving that they are sufficient as well.