Pondo LCA I
View as PDFYou are given a tree with vertices, rooted at vertex
, and
queries. Each query
gives two vertices
and
. Output the lowest common ancestor of
and
.
The lowest common ancestor of and
is the deepest vertex that lies on both the path
from the root to
and the path from the root to
. In particular,
,
and if
is an ancestor of
then
.
Solve the queries with an Euler tour. Unlike the enter/exit tour (first and last visit
only), record a vertex every time you visit it: when you first enter it, and again each
time you return from a child. The lowest common ancestor of and
is then the vertex
of minimum depth on the tour between their first visits.
The bounds are small, so you may scan that range in time per query.
Input
The first line contains two integers and
.
Each of the next lines contains two integers
and
, denoting an undirected
edge between
and
.
Each of the next lines contains two integers
and
, the vertices of one query.
Vertices are numbered through
. The edges form a tree.
Output
Print lines. The
-th line should contain the lowest common ancestor of the
-th
query.
Constraints
Example 1
Input
5 5
1 2
2 3
2 4
1 5
2 5
5 2
3 4
2 3
4 4
Output
1
1
2
2
4
Explanation
The tree, rooted at , looks like this:
1
/ \
2 5
/ \
3 4
Example 2
Input
10 10
4 7
7 8
2 4
6 7
8 10
5 8
2 9
3 7
1 9
2 9
6 8
8 9
2 8
8 9
3 8
4 10
5 7
5 6
3 9
Output
9
7
9
2
9
7
4
7
7
9
Comments