PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000030. Truy vấn tổ tiên chung của cây (LCA)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Truy vấn tổ tiên chung của cây (LCA)

LCA

Source: LQDOJ

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected tree with nn vertices is rooted at vertex 11. Vertex xx is an ancestor of yy if it lies on the unique path from root 11 to yy; each vertex is also its own ancestor.

For each of the qq vertex pairs x,yx,y, find their deepest common ancestor. The tree does not change between queries.

Input

  • First line: nn.
  • Next n−1n-1 lines: edges u,vu,v.
  • Then one line qq.
  • Last qq lines: queries x,yx,y.

Output

Print the LCA for each pair on a separate line.

Subtasks

General constraints (all subtasks): 1≤n,q≤1051\le n,q\le 10^5; 1≤u,v,x,y≤n1\le u,v,x,y\le n.

  • Subtask 1 (20 points): 1≤n≤301\le n\le 30; 1≤q≤501\le q\le 50.
  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000.

Examples

Input

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

Output

3
7
1
1
6
1

Explanation

The first two queries have equal endpoints and return 33 and 77. Queries between branches through root 11 have LCA 11.