This page is still under construction.

Parts of this page are still being built. What you see may change.

Cat and Mouse

Time limit10sMemory limit512 MB

Summary
On a tree with distinct edge weights, the mouse always moves to its heaviest incident edge (or second heaviest if the cat blocks it); find the minimum number of mouse moves for the cat to trap it.
Level

Hard8 of 10

Topics
Tree, DFS, Greedy, Game theory
Solved
No attempts yet

Problem

A cat and a mouse play a game on an undirected tree with NN vertices numbered 11 to NN. The cat starts at vertex 11 and the mouse starts at vertex MM. Every edge of the tree carries cheese, and the amounts are the distinct numbers 11 to N−1N-1. The two animals move alternately, and the mouse moves first.

On its turn the mouse leaves its current vertex along the incident edge with the largest amount of cheese. If the cat stands on that neighboring vertex, the mouse leaves along the incident edge with the second largest amount of cheese instead. If there is no second vertex to move to, the game ends and the cat wins. On its turn the cat moves to a neighboring vertex or stays where it is.

You control the cat and want to win as early as possible. Find the minimum number of moves the mouse makes before the cat wins.

Input

The first line contains the number of test cases TT. The TT test cases follow.

The first line of each test case contains NN and MM. Each of the next N−1N-1 lines contains two integers uu and vv and describes an edge between vertex uu and vertex vv. The kk-th of these edges (1≤k≤N−11 \le k \le N-1) carries kk units of cheese.

Constraints

  • 1≤T≤1001 \le T \le 100
  • 2≤N≤20002 \le N \le 2000
  • 1≤M≤N1 \le M \le N
  • 1≤u,v≤N1 \le u, v \le N
  • The graph of each test case is a tree.
  • The sum of NN over all test cases is at most 50005000.
  • The mouse never eats the cheese, so every edge keeps the same amount for the whole game.
  • The cat may move onto the vertex that holds the mouse. The mouse takes no harm and the game simply continues.

Output

For each test case, in the order given in the input, print one line with the minimum number of moves the mouse makes before the cat wins, assuming the cat plays optimally. Print −1-1 if the cat cannot win.

Examples1

  1. Example 1

    Input
    3
    10 10
    6 7
    6 5
    5 4
    4 1
    1 2
    1 3
    7 8
    8 9
    9 10
    10 6
    6 7
    6 5
    5 4
    4 1
    1 2
    1 3
    7 8
    8 9
    9 10
    13 5
    5 6
    6 7
    7 8
    8 9
    9 10
    10 11
    11 12
    12 13
    5 4
    4 3
    3 1
    1 2
    
    Expected output
    6
    4
    4