#P12153. 【MX-X11-T7】「蓬莱人形 Round 1」信念

【MX-X11-T7】「蓬莱人形 Round 1」信念

Description

Given a rooted tree with nn nodes (numbered 11 to nn, root is node 11).

Each node ii has a pair (depi,stri)(dep_i, str_i) where:

  • depidep_i is the distance from ii to the root.
  • stristr_i is the string formed by concatenating the IDs of all nodes along the simple path from the root to ii (the character set consists of node IDs).

There are qq queries. For each query (x,k)(x, k), compute f(x,k)f(x, k) as follows:

  1. Find the set SS of node IDs in the (x,k)(x, k)-neighborhood.
  2. Sort SS in ascending order by their pairs (using depdep as the primary key and strstr's lexicographical order as the secondary key). Let the sorted list be c1,c2,,cSc_1, c_2, \ldots, c_{|S|}.
  3. f(x,k)f(x, k) is defined as $\sum_{i=1}^{|S|-1} \operatorname{Dis}(c_i, c_{i+1})$.

Definitions:

  • Dis(u,v)\operatorname{Dis}(u, v): The number of edges on the unique simple path between uu and vv.
  • (u,d)(u, d)-neighborhood: The set of nodes whose distance from uu is d\le d.

Input Format

  • First line: Two integers n,qn, q (number of nodes and queries).
  • Second line: n1n-1 integers where the ii-th integer is the parent pi+1p_{i+1} of node i+1i+1.
  • Next qq lines: Two integers x,kx, k per line (query parameters).

Output Format

Output qq lines, each containing the answer to the corresponding query.

10 3
1 2 2 3 4 5 6 6 9 
1 3
3 2
4 3
11
8
15
10 10
1 2 2 3 4 5 6 6 9 
1 3
3 2
4 3
10 3
2 2
3 3
5 3
1 0
7 2
1 2
11
8
15
5
11
16
8
0
2
4

Hint

Explanation #1

The pairs for each node are (where "|" is used only to separate characters in strings):

Node ID Pair
11 (0,1)(0,1)
22 (1,12)(1,1 \mid 2)
33 (2,123)(2,1 \mid 2 \mid 3)
44 (2,124)(2,1\mid 2\mid 4)
55 (3,1235)(3,1\mid 2\mid 3\mid 5)
66 (3,1246)(3,1 \mid 2 \mid 4 \mid 6)
77 (4,12357)(4,1\mid 2\mid 3\mid 5\mid 7)
88 (4,12468)(4,1\mid 2\mid 4\mid 6\mid 8)
99 (4,12469)(4,1\mid 2\mid 4\mid 6\mid 9)
1010 (5,1246910)(5,1\mid 2\mid 4\mid 6\mid 9\mid 10)

For query (1,3)(1, 3):

  • cc sequence: 1,2,3,4,5,61,2,3,4,5,6
  • $f(1,3) = \operatorname{Dis}(1,2)+\operatorname{Dis}(2,3)+\operatorname{Dis}(3,4)+\operatorname{Dis}(4,5)+\operatorname{Dis}(5,6) = 11$.

For query (3,2)(3, 2):

  • cc sequence: 1,2,3,4,5,71,2,3,4,5,7
  • f(3,2)=8f(3,2) = 8.

For query (4,3)(4, 3):

  • cc sequence: 1,2,3,4,5,6,8,9,101,2,3,4,5,6,8,9,10
  • f(4,3)=15f(4,3) = 15.

Constraints

This problem uses subtask scoring.

For all test data: 1n,q5×1051 \le n, q \le 5 \times 10^5, 1pi<i1 \le p_i < i, 1xn1 \le x \le n, 0kn0 \le k \le n.

Subtask n,qn, q \leq Special Property Points
1 10001000 None 5
2 2×1052 \times 10^5 A 25
3 1×1051 \times 10^5 B 10
4 None 15
5 2×1052 \times 10^5
6 5×1055 \times 10^5 30
  • Special Property A: Parent nodes are randomly generated within valid ranges.
  • Special Property B: All leaf nodes have the same depth.

Note: Use fast I/O methods for this problem.

Translated by DeepSeek R1