#5414. Problem 3. Dynamic Instability

0

Problem 3. Dynamic Instability

Problem 3. Dynamic Instability

USACO 2026 Second Contest, Platinum

Farmer Nhoj has trapped Bessie on a rooted tree with NN (2N21052 \le N \le 2 \cdot 10^5) nodes, where node 11 is the root. Scared and alone, Bessie makes the following move each second:

  • If Bessie's current node has no children, then she will move to a random ancestor of the current node (excluding the node itself).
  • Otherwise, Bessie will move to a random child of the current node.

Initially, Bessie is at node xx, and her only way out is the exit located at node yy (1x,yN1\le x,y\le N). For QQ (1Q21051 \le Q \le 2 \cdot 10^5) independent queries of xx and yy, compute the expected number of seconds it would take Bessie to reach node yy for the first time if she started at node xx, modulo 109+710^9+7.

INPUT FORMAT (input arrives from the terminal / stdin):

The first line contains NN and QQ.

The next line contains N1N-1 integers p2,pNp_2, \ldots p_N describing the tree (1pi<i1\le p_i<i). For each 2iN2 \le i \le N, there is an edge between nodes ii and pip_i.

Each of the next QQ lines contains integers xx and yy representing the nodes for that query.

OUTPUT FORMAT (print output to the terminal / stdout):

For each query, output the expected number of seconds for Bessie to reach node yy for the first time starting at node xx, modulo 109+710^9+7.

SAMPLE INPUT:


5 5
1 2 2 1
1 1
2 1
3 1
4 1
5 1

SAMPLE OUTPUT:


0
4
3
3
1

In the 11st query, the expected time to reach node 11 from itself is 00.

In the 33rd query, after 11 second, Bessie will be at node 11 with probability 12\frac{1}{2} and at node 22 with probability 12\frac{1}{2}. Since the expected time to reach node 11 from node 22 is 44, the expected time for Bessie to reach node 11 starting at node 33 is 1+120+124=31 + \frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 4 = 3.

SAMPLE INPUT:


5 5
1 2 2 1
1 1
1 2
1 3
1 4
1 5

SAMPLE OUTPUT:


0
3
500000011
500000011
6

In the 33rd query, the expected time to reach node 33 from node 11 is 152\frac{15}{2}.

SAMPLE INPUT:


13 10
1 2 2 4 3 1 5 6 4 7 8 10
1 12
10 6
5 12
1 13
13 10
6 4
7 12
3 1
12 8
2 1

SAMPLE OUTPUT:


166666700
21
2
166666701
500000023
18
166666704
750000018
800000021
500000018

SCORING: Inputs 4-8: For all queries, y=1y=1.Inputs 9-13: For all queries, x=1x=1.Inputs 14-18: For each 2iN2 \le i \le N, pip_i is uniformly randomly chosen from the range [1,i1][1, i-1]. Inputs 19-23: No additional constraints.

Problem credits: Avnith Vijayram