ENG  RUSTimus Online Judge
Online Judge
Online contests
About Online Judge
Frequently asked questions
Site news
Problem set
Submit solution
Judge status
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests

2109. Tourism on Mars

Time limit: 4.0 second
Memory limit: 300 MB
Few people know, but a long time ago a developed state existed on Mars. It consisted of n cities, numbered by integers from 1 to n, the capital had the number 1. Some pairs of cities were connected by a road. The residents of the state were very prudent, therefore, between any two cities, there was exactly one path (possibly consisting of several roads).
Due to the fact that the state was developed, its residents loved traveling. Tourist route on Mars was described by two numbers L and R. This meant that the tourist started the route in the city L, then went to the city L + 1 (without going into the cities, that did not lie on the path between L and L + 1), then went to the city L + 2, and so on. The last city on the route was the city R. A city that was the closest to the capital among all cities visited on this route (if to count a distance between the cities by the roads) was considered the main attraction of the route.
Knowing the map of the Martian state and all the tourist routes, find for each route its main attraction.


The first line contains an integer n that is the number of cities (1 ≤ n ≤ 2 · 105).
The following n − 1 lines describe the roads. Each road is described by two numbers of cities that are connected by it (1 ≤ viui ≤ n; vi ≠ ui).
The (n + 1)-th line contains an integer q that is the number of tourist routes (0 ≤ q ≤ 106).
Then q lines describe the routes themselves. Each route is described by a pair of integers Li, Ri (1 ≤ LiRin).


Output q integers, one per line — for each route the number of its main attraction. These numbers should be output in the same order in which the respective routes were described.


1 2
1 3
2 4
2 5
2 6
3 7
4 6
3 4
5 7
1 3
3 5
5 6
7 5
1 4
2 4
4 5
5 6
6 7


This problem has a big input and output data size and a strict Time Limit. If you write your solution in C++ we recommend you to use Visual C++ 2013 compiler.
Problem Author: Vladimir Leskov
Problem Source: Ural FU Junior Championship 2016