/ ALGORITHM

# CodeForces Round #425 (Div. 2) D

## Description

Misha and Grisha are funny boys, so they like to use new underground. The underground has $n$ stations connected with $n-1$ routes so that each route connects two stations, and it is possible to reach every station from any other.

The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station $s$ to station $f$ by the shortest path, and will draw with aerosol an ugly text “Misha was here” on every station he will pass through (including $s$ and $f$). After that on the same day at evening Grisha will ride from station $t$ to station $f$ by the shortest path and will count stations with Misha’s text. After that at night the underground workers will wash the texts out, because the underground should be clean.

The boys have already chosen three stations $a$, $b$ and $c$ for each of several following days, one of them should be station $s$ on that day, another should be station $f$, and the remaining should be station $t$. They became interested how they should choose these stations $s$, $f$, $t$ so that the number Grisha will count is as large as possible. They asked you for help.

## Input

The first line contains integer $n\ (1 ≤ n ≤ 3 \times 10^5)$ — the number of vertices in the tree. The second line contains $n - 1$ integers $p_2, p_3, … p_n\ (1 ≤ p_i < i)$, where $p_i$ is the number of the vertex that is the parent of vertex $i$ in the tree.

The first line contains two integers $n$ and $q\ (2 ≤ n ≤ 10^5, 1 ≤ q ≤ 10^5)$ — the number of stations and the number of days.

The second line contains $n - 1$ integers $p_2, p_3, …, p_n\ (1 ≤ p_i ≤ n)$. The integer $p_i$ means that there is a route between stations $p_i$ and $i$. It is guaranteed that it’s possible to reach every station from any other.

The next $q$ lines contains three integers $a, b, c$ each $(1 ≤ a, b, c ≤ n)$ — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

## Output

Print $q$ lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations $s, t, f$ are chosen optimally from the three stations on the $i$-th day.

## Sample Input

3 2
1 1
1 2 3
2 3 3


## Sample Output

2
3


## Solution

• 终点在两个起点的 $Lca(b,c)$ 的子树内：共同路径节点数就是 $Lca(a,b), Lca(a,c)$ 中不等于 $Lca(b,c)$ 的节点到终点的路径的节点数

• 终点在两个起点的 $Lca(b,c)$ 的子树外：共同路径节点数就是 $Lca(b,c))$ 到 $a$ 的路径的节点数

## AC code #### Darron

The professional publishing platform