#P10107. [GDKOI2023 提高组] 树

[GDKOI2023 提高组] 树

Problem Description

Given a rooted tree TT with nn nodes. The nodes are numbered starting from 11. The root is node 11. Each node has a positive integer weight viv_i.

There are QQ queries. For one query, given (x,k)(x, k), let all nodes in the subtree of node xx (including xx itself) whose distance to node xx is at most kk be c1,c2,...,cmc_1, c_2, . . . , c_m. Then the answer to this query is:

$$(v_{c_1} ⊕ d(c_1, x)) + (v_{c_2} ⊕ d(c_2, x)) + \cdots + (v_{c_m} ⊕ d(c_m, x))$$

Here, d(x,y)d(x, y) denotes the number of edges on the unique simple path between nodes xx and yy in the tree, and d(x,x)=0d(x, x) = 0. denotes the XOR operation.

Input Format

The first line contains an integer nn, representing the size of the tree.

The second line contains nn integers, representing viv_i.

The third line contains n1n - 1 integers, in order representing nodes 22 to nn. Each integer is the parent index pip_i of the corresponding node.

The fourth line contains an integer QQ.

The next QQ lines each contain two integers x,kx, k, representing a query (x,k)(x, k).

Output Format

Output QQ lines in total. The ii-th line contains one integer, representing the answer to the ii-th query.

10
9 3 0 7 4 8 8 7 2 5
1 1 2 2 3 6 6 8 7
10
8 2
2 1
5 1
4 1
4 1
1 4
4 1
6 3
4 1
1 4
10
14
4
7
7
55
7
30
7
55

Hint

For 10%10\% of the testdata, n,Q2×103n, Q ≤ 2 \times 10^3.

For 20%20\% of the testdata, n,Q105n, Q ≤ 10^5.

For another 20%20\% of the testdata, pi=i1p_i = i - 1.

For another 10%10\% of the testdata, k20k ≤ 20.

For another 20%20\% of the testdata, k=nk = n.

For another 10%10\% of the testdata, vi=0v_i = 0.

For 100%100\% of the testdata, 1n,Q1061 ≤ n, Q ≤ 10^6, 0v1090 ≤ v ≤ 10^9, 1pi<i1 ≤ p_i < i, 1x,kn1 ≤ x, k ≤ n.

Translated by ChatGPT 5