Under construction

Still being built. Things may change

Trimming the Tree

Time limit1sMemory limit1024 MB

Summary
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 NN vertices and N−1N-1 edges is given. Each vertex of the tree is labeled with a distinct number from 11 to NN. 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.

  1. Choose two adjacent vertices ss and tt in the tree and delete the edge connecting ss and tt. After the deletion, let SS be the tree containing ss and TT be the tree containing tt.
  2. Choose a vertex pp in tree SS.
  3. Add an edge connecting pp and tt to join the two trees back into one tree.

When Donggeon can perform the operation at most KK times, find the diameter of the longest-diameter tree that Donggeon can obtain.

Input

The first line contains two integers NN and KK, separated by a space. (2≤N≤100 0002 \le N \le 100\,000, 0≤K≤100 0000 \le K \le 100\,000)

From the second line onward, the next N−1N-1 lines each contain two integers uu and vv, separated by a space. This means there is an edge between vertex uu and vertex vv. (1≤u,v≤N1 \le u, v \le N, u≠vu \ne v)

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 22 and 44 and delete the edge connecting 22 and 44. After the deletion, let SS be the tree containing 22 and TT be the tree containing 44.

  1. Choose vertex 33 in tree SS.
  2. Add an edge connecting 33 and 44 to join the two trees back into one tree.

Examples4

  1. Example 1

    Input
    4 0
    1 2
    2 3
    2 4
    
    Expected output
    2
    
  2. Example 2

    Input
    4 1
    1 2
    2 3
    2 4
    
    Expected output
    3
    
  3. Example 3

    Input
    10 1
    1 2
    2 3
    3 4
    3 5
    5 6
    2 7
    7 8
    8 9
    9 10
    
    Expected output
    8
    
  4. Example 4

    Input
    7 1
    1 2
    2 3
    2 4
    4 5
    4 6
    6 7
    
    Expected output
    5