Lowest Common Ancestor

AC一覧

Problem Statement問題文

Given a rooted tree with $N$ vertices. The root is vertex $0$ and a parent of a vertex $i$ is $p_i$. Process $Q$ queries as follows:

• $u$ $v$: Print LCA of vertex $u$ and $v$.

• $u$ $v$: 頂点 $u$, $v$ のLCAを出力する

Constraints制約

• $2 \leq N \leq 500,000$
• $1 \leq Q \leq 500,000$
• $0 \leq p_i < i$
• $0 \leq u < v \leq N - 1$

Input入力

$N$ $Q$
$p_1$ $p_2$ ... $p_{N-1}$
$u_0$ $v_0$
$u_1$ $v_1$
:
$u_{Q - 1}$ $v_{Q - 1}$


Sampleサンプル

# 1

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

0
0
0
2
2


Timelimit: 5 secs

Before submitting, please confirm terms and conditions