#LCA0000069. Tổ tiên chung khi đổi gốc (LCA with Changing Root)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Tổ tiên chung khi đổi gốc (LCA with Changing Root)
LCA with Changing Root
Source: CodeChef
Version: Phuoc Hung OJ Extended
Problem Statement
An undirected tree has vertices. Each query temporarily roots the tree at and asks for the lowest common ancestor of and under that root. Queries are independent: changing the root only changes parent/ancestor relations, never the edges. The LCA is the deepest common vertex on the paths from the chosen root to and .
Input
First line is , followed by edges . Next line is , followed by queries .
Output
For each query print the LCA index when rooted at .
Subtasks
General constraints: ; ; đầu vào là cây.
-
Subtask 1 (20 points): ; .
-
Subtask 2 (30 points): ; .
-
Subtask 3 (50 points): ; .
Examples
Input
4
1 2
2 3
1 4
2
1 4 2
2 4 2
Output
1
2
Explanation
With root , the LCA of and is . With root , vertex is an ancestor of both query vertices.