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

Odd-Degree Graph

Back to problem

Editorial

Subtask 1: enumerate all subsets of the (N2)\binom{N}{2}(2N​) possible edges. Check the edge bound, connectivity, and number of odd-degree vertices. This takes O(2(N2)N2)O(2^{\binom{N}{2}}N^2)O(2(2N​)N2) time and O(N2)O(N^2)O(N2) space.

Full solution: the sum of degrees equals twice the number of edges and is therefore even. Hence an odd KKK is impossible. This also handles N=1N=1N=1, since then K=1K=1K=1.

If KKK is even, then K≥2K\geq2K≥2. First connect vertex 111 to every vertex 2,3,…,K2,3,\ldots,K2,3,…,K. Vertex 1 has odd degree , and the other vertices have degree . Exactly vertices have odd degree.

Attach the remaining vertices as a path starting at vertex KKK: add (K,K+1),(K+1,K+2),…,(N−1,N)(K,K+1),(K+1,K+2),\ldots,(N-1,N)(K,K+1),(K+1,K+. Each added vertex changes the old endpoint's degree from to and creates a new endpoint of degree , preserving the number of odd-degree vertices.

The result is a connected tree without loops or multiple edges. It has (K−1)+(N−K)=N−1(K-1)+(N-K)=N-1(K−1)+(N−K)=N−1 edges, satisfying the output bound. If K=NK=NK, no path edges are added.

The solution takes O(N)O(N)O(N) time and O(1)O(1)O(1) extra space, excluding output buffers. The checker uses an ordered set for duplicate edges and a disjoint-set structure for connectivity, taking O(N+Mlog⁡(M+1))O(N+M\log(M+1))O(N+Mlog(M+ time and space. Since , all arithmetic fits in signed 64-bit integers.

Solution written by GPT

1
1
K−1K-1K−1
K−1K-1K−1
111
KKK
2
)
,
…
,
(
N
−
1,N)
111
222
111
=
N
1))
O(N+M)O(N+M)O(N+M)
M≤2NM\leq2NM≤2N