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

#LCA0000071. Truy vấn tổ tiên theo đoạn nhãn (LCA Range Queries)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Truy vấn tổ tiên theo đoạn nhãn (LCA Range Queries)

LCA Range Queries

Source: LQDOJ

Version: Phuoc Hung OJ Extended

Problem Statement

A tree of nn vertices labeled 1,2,…,n1,2,\ldots,n is rooted at vertex 11. Given l≤rl\le r, find the lowest common ancestor of all vertices with consecutive labels l,l+1,…,rl,l+1,\ldots,r. This interval is over vertex labels, not path positions or DFS-entry times. When l=rl=r, the answer is vertex ll.

Input

First line: nn, then n−1n-1 edges u vu\ v. Next line: qq, then qq queries l rl\ r.

Output

Print one integer (the LCA vertex label) per query.

Subtasks

General constraints: 1≤n,q≤1051\le n,q\le 10^5; 1≤l≤r≤n1\le l\le r\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

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

Output

4
1

Explanation

The LCA of vertices labeled 2,3,42,3,4 is vertex 44. Since labels 1,2,31,2,3 include the root itself, their LCA is 11.