Under construction

Still being built. Things may change

LCA and Queries

Time limit5sMemory limit1536 MB

Summary
Given a rooted tree and several queries, each listing K vertices, compute the sum of the LCA levels over all pairs of those vertices.
Level

Medium6 of 10

Topics
Tree, Sorting, DFS
Solved
No attempts yet

Problem

For a tree TT with NN vertices, write a program that processes the following query.

  • K V1 V2 ⋯ VKK \ V_1 \ V_2 \ \cdots \ V_K: For every pair (i,j)(i, j) with 1≤i<j≤K1 \leq i < j \leq K, print the sum of the levels of the LCA of vertex ViV_i and vertex VjV_j.

The root of TT is vertex 1. The root has level 0, and every other vertex has level (level of its parent) + 1.

The LCA of two vertices uu and vv is the closest common ancestor of uu and vv (the lowest common ancestor).

Input

The first line contains the number of vertices NN and the number of queries QQ.

The second line contains the parent vertices P2,P3,⋯ ,PNP_2, P_3, \cdots, P_N of vertices 2,3,⋯ ,N2, 3, \cdots, N.

Each of the next QQ lines contains a query K V1 V2 ⋯ VKK \ V_1 \ V_2 \ \cdots \ V_K, with the values separated by spaces.

Output

For each query, print the result on its own line.

Constraints

  • 2≤N≤500 0002 \leq N \leq 500\,000
  • 1≤Q≤500 0001 \leq Q \leq 500\,000
  • For 2≤i≤N2 \leq i \leq N, 1≤Pi<i1 \leq P_i < i
  • 2≤K≤N2 \leq K \leq N
  • The sum of KK over all queries is at most 1 000 0001\,000\,000
  • 1≤Vi≤N1 \leq V_i \leq N
  • If i≠ji \neq j, then Vi≠VjV_i \neq V_j

Examples1

  1. Example 1

    Input
    16 4
    1 2 3 4 3 1 7 8 9 7 11 12 1 14 15
    2 4 5
    2 10 13
    3 4 6 16
    4 4 10 6 13
    
    Expected output
    3
    1
    2
    3