PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#DSU0000094. Tổ tiên chung gần nhất (Nearest Common Ancestors)
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 gần nhất (Nearest Common Ancestors)
Nearest Common Ancestors
Source: POJ
Version: Phuoc Hung OJ Extended
Problem Statement
Given a rooted tree of vertices numbered through . Every edge indicates that is the direct parent of . The root is the unique vertex without a parent. For two distinct vertices , find their lowest common ancestor: the deepest vertex lying on both root-to-vertex paths. A vertex is considered its own ancestor.
Input
The first line contains . Each of the next lines gives a parent–child pair . The last line contains .
Output
Print the lowest common ancestor of and .
Subtasks
- Subtask 1 (20 points): ; edges form a rooted tree, , .
- Subtask 2 (30 points): ; edges form a rooted tree, , .
- Subtask 3 (50 points): ; edges form a rooted tree, , .
Examples
Input
5
2 3
3 4
3 1
1 5
3 5
Output
3
Explanation
Vertex is the lowest common ancestor of vertices and .