#abc351g. G - Hash on Tree
G - Hash on Tree
Score: points
问题陈述
给定一个有根树,有 个顶点,编号为 到 。 顶点 是根,顶点 的父顶点 是顶点 。 此外,还有一个序列 。
有根树的 哈希值 计算如下:
- 定义 如下,按顺序 。
- 如果顶点 是叶子,。
- 如果顶点 不是叶子,,其中 是 的子顶点集合。
- 有根树的哈希值是 。
按给定顺序处理 个查询。 每个查询提供 和 ,因此更新 为 ,然后计算有根树的哈希值。
以上为大语言模型 kimi 翻译,仅供参考。
Problem Statement
You are given a rooted tree with vertices numbered to .
Vertex is the root, and the parent of vertex is vertex .
Additionally, there is a sequence .
The hash value of the rooted tree is calculated as follows:
- Define as follows in the order .
- If vertex is a leaf, .
- If vertex is not a leaf, , where is the set of children of .
- The hash value of the rooted tree is .
Process queries in the order they are given.
Each query provides and , so update to and then compute the hash value of the rooted tree.
Constraints
- All input values are integers.
Input
The input is given from Standard Input in the following format, where represents the -th query:
Each query is given in the following format:
Output
Print lines. The -th line should contain the answer to the -th query.
Sample Input 1
3 2
1 1
3 5 1
3 4
2 1
Sample Output 1
23
7
Initially, .
The first query is processed as follows:
- Update to . Now .
- The hash value of the rooted tree is calculated as follows to be , which should be printed.
- Vertex has no children. Thus, .
- Vertex has no children. Thus, .
- Vertex has children and . Thus, .
- is the hash value of the rooted tree.
The second query is processed as follows:
- Update to . Now .
- The hash value of the rooted tree is calculated as follows to be :
- Vertex has no children. Thus, .
- Vertex has no children. Thus, .
- Vertex has children and . Thus, .
- is the hash value of the rooted tree.
Sample Input 2
5 4
1 1 2 2
2 5 4 4 1
3 3
5 0
4 5
5 2
Sample Output 2
29
17
17
47
Sample Input 3
10 10
1 2 1 2 5 6 3 5 1
766294629 440423913 59187619 725560240 585990756 965580535 623321125 550925213 122410708 549392044
1 21524934
9 529970099
6 757265587
8 219853537
5 687675301
5 844033519
8 780395611
2 285523485
6 13801766
3 487663184
Sample Output 3
876873846
952166813
626349486
341294449
466546009
331098453
469507939
414882732
86695436
199797684