Maximum Safety

4

22 votes
Medium-Hard
Problem

Kevin wants to hide from Marv in the city. The city consists of N junctions connected with roads. There are N1 roads, each of length 1. So the city is a tree. Root of this tree is junction 1.

For each of the next M days Kevin wants to hide in one of the junctions. Kevin knows that Marv is located in junction ai on the i-th day. Kevin also believes that junction v is safe only if v is in the subtree of vertex bi. The safety of vertex v is equal to the distance between v and ai. Help Kevin to find the maximum safety possible for each day.

Input format:

The first line of input will contain an integer T, denoting the number of test cases.
Each test case starts with 2 numbers N and M. Next N1 lines contains 2 numbers ui and vi - junctions connected by a road. Next M lines contains 2 numbers ai and bi. To find actual values of ai and bi Kevin does the following steps:

  • let di1 be the answer on i1-th day.
  • ai=((ai1+di1) mod N)+1
  • bi=((bi1+di1) mod N)+1
  • assume that d0=0

Output format:

For every test case output M numbers - maximum safety for each day.

Constraints:

  • 1T10
  • (20 points): 1N1000,1M1000
  • (30 points): 1N105,1M105 , ai is not in the subtree of bi.
  • (50 points): 1N105,1M105.
Sample Input
1
7 4
1 2
1 3
1 4
4 5
4 6
5 7
2 4
1 7
1 1
4 1
Sample Output
4
2
0
2
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

Actual values of ai and bi:
Day 1 : a1=2,b1=4
Day 2 : a2=5,b1=4
Day 3 : a1=3,b1=3
Day 4 : a1=4,b1=1

Tree from the sample case:

sample

On the first day junction 7 has the maximum safety and its distance from junction 2 is 4. On the second day junction 6 has the maximum safety and its distance from junction 5 is 2. Note that distance to junction 2 is 3 but junction 2 is not safe as it is not in the subtree of juntion 4.

Editor Image

?