Trimming the Tree
Time limit1sMemory limit1024 MB
Given a tree and at most K operations that cut an edge and reattach one side to a vertex on the other side, find the largest diameter reachable.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, DFS, Greedy
- Solved
- No attempts yet
Problem
A tree with vertices and edges is given. Each vertex of the tree is labeled with a distinct number from to . The length of every edge in the tree is 1.
The diameter of a tree is the maximum distance among all pairs of distinct vertices in the tree.
Donggeon can perform the following operation on the tree. One operation consists of the three steps below, performed in order.
- Choose two adjacent vertices and in the tree and delete the edge connecting and . After the deletion, let be the tree containing and be the tree containing .
- Choose a vertex in tree .
- Add an edge connecting and to join the two trees back into one tree.
When Donggeon can perform the operation at most times, find the diameter of the longest-diameter tree that Donggeon can obtain.
Input
The first line contains two integers and , separated by a space. (, )
From the second line onward, the next lines each contain two integers and , separated by a space. This means there is an edge between vertex and vertex . (, )
Every edge of the tree is given exactly once.
Output
On the first line, print the diameter of the longest-diameter tree that Donggeon can obtain.
Hint
Perform one operation on the tree below.

1. Choose two adjacent vertices and and delete the edge connecting and . After the deletion, let be the tree containing and be the tree containing .

- Choose vertex in tree .
- Add an edge connecting and to join the two trees back into one tree.
