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
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
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 vertices is rooted at vertex . Vertex is an ancestor of if it lies on the unique path from root to ; each vertex is also its own ancestor.
For each of the vertex pairs , find their deepest common ancestor. The tree does not change between queries.
Input
- First line: .
- Next lines: edges .
- Then one line .
- Last lines: queries .
Output
Print the LCA for each pair on a separate line.
Subtasks
General constraints (all subtasks): ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
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 and . Queries between branches through root have LCA .