LearnPy Hub
← Arena
AdvancedRating 1700

Lowest Common Ancestor

The tree is rooted at node 1. For each query (u, v), print their lowest common ancestor: the deepest node that is an ancestor of both (a node counts as its own ancestor).

Input

n; n − 1 edges; q; q lines 'u v'.

Output

q lines.

Sample 1

Input
7
1 2
1 3
2 4
2 5
3 6
3 7
4
4 5
4 6
3 7
1 1
Output
2
1
3
1

Sample 2

Input
15
1 7
7 3
7 6
3 13
13 11
7 15
15 10
13 4
3 5
4 12
12 14
14 9
9 2
12 8
20
6 12
8 11
12 10
3 8
14 2
4 11
4 10
3 12
2 5
6 11
14 12
9 2
3 2
11 13
12 1
15 2
10 13
12 14
5 6
8 12
Output
7
13
7
3
14
13
7
3
3
7
12
9
3
13
1
7
7
12
7
12
solution.py
Output appears here
Lowest Common Ancestor · Python Arena problem · LearnPy Hub