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

Spliting a tree

Back to problem

Editorial

Let deg⁡(v)\deg(v)deg(v) denote the degree of vertex vvv.

If deg⁡(v)≥2\deg(v) \geq 2deg(v)≥2, the answer is 000. Removing only vvv separates the tree into exactly deg⁡(v)\deg(v)deg(v) connected components, one for each direction incident to vvv.

Now suppose that vvv is a leaf. Let bbb be the nearest vertex of degree at least 333, and let ddd be the distance between vvv and bbb.

For every k<dk<dk<d, the removed vertices form one simple path starting at vvv. Before reaching its endpoint, this path contains no vertex of degree at least 333, so the remaining graph is connected or empty. It cannot have at least two connected components.

For k=dk=dk=d, vertex bbb is also removed. Even after excluding the direction from bbb toward vvv, at least two other directions remain incident to bbb. After removing bb, those directions belong to different connected components. Therefore the answer for the leaf is .

If the tree has no vertex of degree at least 333, it is a path. Removing any radius around a leaf leaves another path or the empty graph, so the answer is −1-1−1. The same conclusion applies when N=1N=1N=1.

Thus the answers are characterized as follows.

  • A vertex of degree at least 222 has answer 000.
  • A leaf has answer equal to its distance from the nearest vertex of degree at least 333. If no such vertex exists, its answer is −1-1−1.
  • A vertex of degree 000 has answer −1-1−1.

Run a multi-source BFS starting from every vertex of degree at least 333. This computes the distance from every vertex to its nearest such vertex in one traversal.

The time complexity is O(N)O(N)O(N), and the memory complexity is O(N)O(N)O(N).

b
vvv
ddd