Cat and Mouse
Time limit10sMemory limit512 MB
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 vertices numbered to . The cat starts at vertex and the mouse starts at vertex . Every edge of the tree carries cheese, and the amounts are the distinct numbers to . 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 . The test cases follow.
The first line of each test case contains and . Each of the next lines contains two integers and and describes an edge between vertex and vertex . The -th of these edges () carries units of cheese.
Constraints
- The graph of each test case is a tree.
- The sum of over all test cases is at most .
- 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 if the cat cannot win.