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

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

1 lộ trình

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 nn vertices and a root ss specified in the input (the root is not necessarily vertex 1). Every non-root vertex's parent is its adjacent vertex toward ss.

For each query (u,v)(u,v), find their lowest common ancestor under this rooting. If u=vu=v, return uu.

Input

  • First line: n,m,sn,m,s.
  • Next n−1n-1 lines: undirected edges x,yx,y.
  • Last mm lines: query vertices u,vu,v.

Output

Print one LCA per query.

Subtasks

General constraints (all subtasks): 1≤n,m≤5⋅1051\le n,m\le 5\cdot10^5; 1≤s,u,v≤n1\le s,u,v\le n.

  • Subtask 1 (20 points): 1≤n≤301\le n\le 30; 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≤5000001\le n\le 500000; 1≤q≤5000001\le q\le 500000.

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 44, the LCA of 33 and 55 is 11. Queries spanning branches attached to root 44 have LCA 44.