PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000034. Tổ tiên chung trên cây gốc 0 (Lowest Common Ancestor)
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 gốc 0 (Lowest Common Ancestor)
Lowest Common Ancestor
Source: AOJ
Version: Phuoc Hung OJ Extended
Problem Statement
You are given a tree rooted at vertex , with vertices indexed through . For each node, its direct children are listed. For each pair , find the deepest vertex that is an ancestor of both.
Every node counts as its own ancestor. Vertex indices start at , and the tree may be very deep.
Input
- First line: .
- The next lines describe vertex with and then its child indices.
- Next line: .
- Next lines: .
Output
Print each query LCA.
Subtasks
General constraints (all subtasks): ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
Examples
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0
Explanation
Vertices have LCA . Vertices belong to separate branches of root , giving LCA .