LCA and Queries
Time limit5sMemory limit1536 MB
Given a rooted tree and several queries, each listing K vertices, compute the sum of the LCA levels over all pairs of those vertices.
Problem
For a tree with vertices, write a program that processes the following query.
- : For every pair with , print the sum of the levels of the LCA of vertex and vertex .
The root of is vertex 1. The root has level 0, and every other vertex has level (level of its parent) + 1.
The LCA of two vertices and is the closest common ancestor of and (the lowest common ancestor).
Input
The first line contains the number of vertices and the number of queries .
The second line contains the parent vertices of vertices .
Each of the next lines contains a query , with the values separated by spaces.
Output
For each query, print the result on its own line.
Constraints
- For ,
- The sum of over all queries is at most
- If , then