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

Connecting a Graph

Back to problem

Editorial

Let KKK be the number of connected components of the graph.

Adding one edge between two different connected components merges those two components, so one added edge can decrease the number of components by at most 111. To make the whole graph connected, only one component must remain, so at least K−1K-1K−1 edges are necessary.

Conversely, choose one representative vertex from each connected component and connect these representatives in a chain. This uses exactly K−1K-1K−1 new edges and makes the graph connected. Therefore, the answer is K−1K-1K−1.

The number of connected components can be found with a disjoint set union data structure. Initially, every vertex is in its own set. For each input edge (ui,vi)(u_i,v_i)(ui​,vi​), merge the sets containing the two endpoints. Finally, count the number of distinct representatives.

The time complexity is O((N+M)α(N))O((N+M)\alpha(N))O((N+M)α(N)).

Solution written by GPT5.5