PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000069. Tổ tiên chung khi đổi gốc (LCA with Changing Root)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

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 nn vertices. Each query (r,u,v)(r,u,v) temporarily roots the tree at rr and asks for the lowest common ancestor of uu and vv 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 uu and vv.

Input

First line is nn, followed by n−1n-1 edges u vu\ v. Next line is qq, followed by qq queries r u vr\ u\ v.

Output

For each query print the LCA index when rooted at rr.

Subtasks

General constraints: 1≤n,q≤1051\le n,q\le 10^5; 1≤r,u,v≤n1\le r,u,v\le n; đầu vào là cây.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤q≤501\le q\le 50.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000.

Examples

Input

4
1 2
2 3
1 4
2
1 4 2
2 4 2

Output

1
2

Explanation

With root 11, the LCA of 44 and 22 is 11. With root 22, vertex 22 is an ancestor of both query vertices.