Editorial
Let denote the degree of vertex .
If , the answer is . Removing only separates the tree into exactly connected components, one for each direction incident to .
Now suppose that is a leaf. Let be the nearest vertex of degree at least , and let be the distance between and .
For every , the removed vertices form one simple path starting at . Before reaching its endpoint, this path contains no vertex of degree at least , so the remaining graph is connected or empty. It cannot have at least two connected components.
For , vertex is also removed. Even after excluding the direction from toward , at least two other directions remain incident to . After removing , those directions belong to different connected components. Therefore the answer for the leaf is .
If the tree has no vertex of degree at least , it is a path. Removing any radius around a leaf leaves another path or the empty graph, so the answer is . The same conclusion applies when .
Thus the answers are characterized as follows.
- A vertex of degree at least has answer .
- A leaf has answer equal to its distance from the nearest vertex of degree at least . If no such vertex exists, its answer is .
- A vertex of degree has answer .
Run a multi-source BFS starting from every vertex of degree at least . This computes the distance from every vertex to its nearest such vertex in one traversal.
The time complexity is , and the memory complexity is .