#P6782. Count Pairs with Given LCA

    ID: 19989 Type: Default 1000ms 256MiB

Count Pairs with Given LCA

Count Pairs with Given LCA

You are given a rooted tree with n nodes. The nodes are numbered from 1 to n, and the tree is rooted at node 1. You are also given m queries. Each query contains three integers l, r, and x. For each query, count the number of pairs of nodes (i, j) such that:

  • l ≤ i < j ≤ r, and
  • The lowest common ancestor (LCA) of nodes i and j is node x.

The LCA of two nodes in a rooted tree is defined as the deepest node (i.e. the node with maximum depth) that is an ancestor of both nodes.

Note: If a mathematical formula is needed, please use LaTeX format. For example, the LCA condition can be written as:

$$LCA(i,j)=x$$

inputFormat

The first line contains two integers n and m — the number of nodes and the number of queries.

The second line contains n-1 integers: p2, p3, \dots, pn, where pi is the parent of node i (node 1 is the root and has no parent).

The following m lines each contain three integers l, r, and x describing a query.

outputFormat

For each query, output a single integer — the number of pairs (i, j) satisfying the conditions, each on a new line.

sample

5 2
1 1 2 2
1 5 1
2 5 2
7

3

</p>