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

Dismantling

Back to problem

Editorial

Give each edge (u,v)(u,v)(u,v) weight ∣Wu−Wv∣|W_u-W_v|∣Wu​−Wv​∣ and use Kruskal's algorithm to find a minimum spanning tree FFF. The minimum cost is

∑(u,v)∈Emin⁡(Wu,Wv)+∑(u,v)∈F∣Wu−Wv∣.\sum_{(u,v)\in E}\min(W_u,W_v) +\sum_{(u,v)\in F}|W_u-W_v|.(u,v)∈E∑​min(W

Output an order that removes all edges outside this tree first, then the tree edges. The order within each part is arbitrary.

The time complexity is O(N+Mlog⁡M)O(N+M\log M)O(N+MlogM) and the space complexity is O(N+M)O(N+M)O(N+M).

Proof

Exactly N−1N-1N−1 removals increase the number of connected components. If we reverse the process, these edges join different components and connect all vertices. Thus, they form a spanning tree.

Charge every edge a base cost of min⁡(Wu,Wv)\min(W_u,W_v)min(Wu​,W. An edge in this tree costs instead, adding . The base cost is fixed, so a minimum spanning tree minimizes the additional cost and gives a lower bound.

u
​
,
Wv​
)
+
(u,v)∈F∑​∣Wu​−
Wv​∣.
v
​
)
max⁡(Wu,Wv)\max(W_u,W_v)max(Wu​,Wv​)
∣Wu−Wv∣|W_u-W_v|∣Wu​−Wv​∣

During the first part of the proposed removal order, the surviving tree keeps the graph connected. During the second part, the remaining graph is a forest, so every removal disconnects its endpoints. This order attains the lower bound.