PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000032. Tổ tiên chung trên cây đánh số từ 0 (Lowest Common Ancestor (0-indexed))
HỌC THEO LỘ TRÌNH
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
Tổ tiên chung trên cây đánh số từ 0 (Lowest Common Ancestor (0-indexed))
Lowest Common Ancestor (0-indexed)
Source: SPOJ
Version: Phuoc Hung OJ Extended
Problem Statement
A tree has vertices indexed from to , rooted at vertex . The input directly lists each node's children. Answer lowest-common-ancestor queries on node pairs .
Here vertex 0 is a valid node and is the root; it is not a missing-node sentinel. For equal query endpoints, the answer is the endpoint itself.
Input
- First line: .
- Next lines describe vertices with child count followed by their indices.
- Next line: .
- Last lines: .
Output
Print one answer per line.
Subtasks
General constraints (all subtasks): ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
Examples
Input
3
2 1 2
0
0
3
1 2
1 1
2 2
Output
0
1
2
Explanation
Vertex is the common ancestor of and . Same-vertex queries return and respectively.