#P6041. 「ACOI2020」布丁暗杀计划

「ACOI2020」布丁暗杀计划

Description

Finally, the students finished the pudding. Kaede, who loves pudding the most, started thinking: how tasty is this pudding?

How tasty a pudding is depends on the flavor-changing ingredients inside. Different ingredients have different colors and tastiness values.

There are nn kinds of flavoring ingredients in the pudding, connected by n1n-1 links. The first ingredient is at the top, which is the root of this tree.

Now, Kaede defines that the tastiness of the pudding depends on two given values u,ku, k. This tastiness is defined as follows: let vv be the kk-th ancestor of ingredient uu. Consider all kk-th level children of ingredient vv, and among them, take those kk-th level children whose color is the same as the color of ingredient vv. The answer is the sum of the tastiness values of these selected nodes. It can be seen that when uu or kk changes, in general the tastiness value also changes. Therefore, there are qq queries to ask you.

In particular, if ingredient uu does not have a kk-th ancestor, output 00 directly.

Input Format

The first line contains two integers n,qn, q, meaning there are nn ingredients and qq queries.

The second line contains nn integers. The ii-th integer represents the color of ingredient ii, coloricolor_i.

The third line contains nn integers. The ii-th integer represents the tastiness value of ingredient ii, did_i.

The fourth line contains n1n-1 integers. The ii-th integer represents the parent node of the ingredient i+1i+1, faifa_i.

The next qq lines each contain two integers u,ku, k, representing a query.

Output Format

There are qq lines, each containing one integer, representing the answer to the query.

3 1
1 1 1
1 2 3
1 1
2 1

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

0
6
0

Hint

Sample Explanation #1

The 11-st ancestor of ingredient 22 is ingredient 11. The 11-st level children of ingredient 11 are ingredients 22 and 33. The colors of ingredients 22 and 33 are both the same as the color of ingredient 11, so the sum of tastiness values is 2+3=52 + 3 = 5.


Constraints

This problem uses bundled testdata.

  • Subtask 1 (30 points): Eggs are scarce, the pudding is small: n103n \leq 10^3, q104q \leq 10^4.
  • Subtask 2 (20 points): The ingredients form a chain: n5×105n \leq 5 \times 10^5, q105q \leq 10^5, colori102color_i \leq 10^2.
  • Subtask 3 (50 points): No special restrictions on the testdata.

For 100%100\% of the testdata, 1n,q,colori5×1051 \leq n, q, color_i \leq 5 \times 10^5, 1di1051 \leq d_i \leq 10^5.


Hint

The time limit for the test points in Subtask 2 and Subtask 3 is 2S.

Translated by ChatGPT 5