#P5305. [GXOI/GZOI2019] 旧词

[GXOI/GZOI2019] 旧词

Description

Life is but three thousand dreamlike scenes.
I have searched a thousand miles, yet poetry and wine are barren.
I only pour out my ideals in vain,
Better to return home early.

Warm a pot of dusty-world wine,
Drink alone as the past stretches far away.
Raise the cup and think lightly,
Tears surge like tides, black hair left in a distant land.

— Wuzhaoshou / Yuqing, "Old Words"

You have already solved five problems. Now, under this big tree, you may as well sing an old song to express your feelings. The last problem is about this tree, and its description is very simple.

Given a rooted tree with nn nodes, with nodes labeled 1n1 \sim n, and node 11 as the root.
Given a constant kk.
Given QQ queries, each query provides x,yx, y.
Compute:

$$\sum\limits_{i \le x} \text{depth}(\text{lca}(i,y))^k$$

lca(x,y)\text{lca}(x,y) denotes the lowest common ancestor of nodes xx and yy in the rooted tree.
depth(x)\text{depth}(x) denotes the depth of node xx, where the root has depth 11.
Since the answer may be very large, you only need to output the result modulo 998244353998244353.

Input Format

The input contains n+Qn+Q lines.

Line 11 contains three positive integers n,Q,kn, Q, k.

For lines i=2ni = 2 \sim n, each line contains a positive integer fi(1fin)f_i(1 \le f_i \le n), which denotes the label of the parent of node ii.

Next come QQ lines, each containing two positive integers x,y(1x,yn)x, y(1 \le x,y \le n), representing one query.

Output Format

The output contains QQ lines, each with one integer, which is the answer modulo 998244353998244353.

5 5 2
1
4
1
2
4 3
5 4
2 5
1 2
3 2
15
11
5
1
6

Hint

Sample Explanation

The tree in the input:

poetry.png

The depths of the nodes are 1,2,3,2,31,2,3,2,3, respectively.

For the first query x=4,y=3x = 4, y = 3, it is easy to compute:

$$\text{lca}(1, 3) = 1,\text{lca}(2, 3) = 1,\text{lca}(3, 3) = 3,\text{lca}(4, 3) = 4$$

So $\text{depth}(1)^2+\text{depth}(1)^2+\text{depth}(3)^2+\text{depth}(4)^2 = 1+1+9+4 = 15$.

Constraints

Test Point ID Size of nn Size of QQ Size of kk Note
11 n2,000n \le 2,000 Q2,000Q \le 2,000 1k1091 \le k \le 10^9 None
22
33
44
55 n50,000n \le 50,000 Q50,000Q \le 50,000 There exists a node whose depth is nn
66
77
88
99 Q=nQ = n For the ii-th query, x=ix = i
1010
1111 Q50,000Q \le 50,000 k=1k = 1 None
1212
1313 k=2k = 2
1414
1515 k=3k = 3
1616
1717 1k1091 \le k \le 10^9
1818
1919
2020

Translated by ChatGPT 5