Fast LCA

View as PDF

Submit solution

Points: 12
Time limit: 2.0s
Memory limit: 40M

Author:
Problem types

Recently, Angie's math teacher began teaching the class about trees (the graph theory kind, of course). As homework, he gave everyone a rooted tree of N nodes (the root node is 1) and asked them to do Q LCA queries on the tree (each query is in the form x y, and its answer is the LCA of nodes x and y in the tree). Since he didn't have the funds to make proper test data for his trees, he generated them randomly with the following algorithm: for every node i (2iN), he picked a uniform random integer in the range [1,i) to be its parent node.

Angie is feeling very demotivated and doesn't want to do her work. Can you solve the queries for her?

Constraints

2x,yN6×106

1Q106

1pi<i for all 2iN

Input Specification

The first line contains the integers N and Q.

The second line contains N1 integers p2,p3,,pN, the parents of nodes 2,3,,N respectively. Note that node 1 does not have a parent as it's the root node of the tree.

The next Q lines each contain a query of the form x y.

Output Specification

For each query, output its answer on a new line.

Sample Input

Copy
10 5
1 2 1 1 4 2 1 6 9
3 9
10 7
4 4
1 3
2 3

Sample Output

Copy
1
1
4
1
2

Explanation

The tree from the sample input:


Comments

There are no comments at the moment.