Pondo Tree Distance
View as PDF
Submit solution
Points:
100
Time limit:
2.0s
PyPy 3
5.0s
Python 3
5.0s
Memory limit:
500M
Problem type
You are given a tree with vertices and
queries. Each query gives two vertices
and
. Output the number of edges on the unique path between
and
.
This is a follow-up to Pondo LCA II. Root the tree at vertex , then
.
In particular, . Use an Euler tour to compute the lowest common
ancestors.
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 endpoints of one path.
Vertices are numbered through
. The edges form a tree.
Output
Print lines. The
-th line should contain the distance between the two vertices of
the
-th query.
Constraints
Example 1
Input
5 6
1 2
2 3
2 4
1 5
2 5
5 2
3 5
3 4
2 3
4 4
Output
2
2
3
2
1
0
Explanation
The tree looks like this:
1
/ \
2 5
/ \
3 4
Rooted at , the depths of vertices
are
. Then
, and
.
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
1
2
4
3
4
2
3
2
3
4
Comments