PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000029. Tổ tiên chung gần nhất với gốc bất kỳ (LCA Template (Arbitrary Root))
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 với gốc bất kỳ (LCA Template (Arbitrary Root))
LCA Template (Arbitrary Root)
Source: Luogu
Version: Phuoc Hung OJ Extended
Problem Statement
You are given an undirected tree with vertices and a root specified in the input (the root is not necessarily vertex 1). Every non-root vertex's parent is its adjacent vertex toward .
For each query , find their lowest common ancestor under this rooting. If , return .
Input
- First line: .
- Next lines: undirected edges .
- Last lines: query vertices .
Output
Print one LCA per query.
Subtasks
General constraints (all subtasks): ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
Examples
Input
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
Output
4
4
1
4
4
Explanation
With root , the LCA of and is . Queries spanning branches attached to root have LCA .