#P9775. [HUSTFC 2023] 广义线段树
[HUSTFC 2023] 广义线段树
Problem Description
For any sequence of length , we can build a generalized segment tree based on . A generalized segment tree is a weighted binary tree with nodes. For each node with index , it has two attributes and , meaning that the interval it maintains is , and its weight is . In addition, the generalized segment tree also satisfies the following properties:
- All nodes with index are leaf nodes, and .
- All nodes with index are non-leaf nodes. Each of them must have a left child and a right child , and . The interval maintained by node is the union of the intervals maintained by its two children, and it is guaranteed to be continuous. Formally, , and , .
For example, the following is a generalized segment tree built from and the sequence (the integer pair inside each node denotes its index and weight, respectively). You can see that the shape of a generalized segment tree is not unique.

For this generalized segment tree:
- , so
- , so
- , so
- , so
- , so
- , so
- , so
You are given two sequences and of length , and the shape of a generalized segment tree with nodes (that is, the indices of the left and right child for each node). Then you need to perform operations. In the -th operation, change into .
After each operation, you need to build a generalized segment tree with the same shape as based on the modified sequence , and compute the sum of weights of all nodes, i.e. . Since the result can be very large, you only need to output it modulo .
Input Format
The first line contains an integer , representing the length of sequences and .
The second line contains integers, where the -th integer is defined as .
The third line contains integers, where the -th integer is defined as .
The next lines describe the tree. The -th of these lines contains two integers , representing the indices of the left and right child of node , respectively. It is guaranteed that the given generalized segment tree shape satisfies the requirements in the statement.
Output Format
Output one line with integers separated by spaces, where the -th integer is the answer after the -th modification modulo .
4
1 2 3 4
2 3 2 3
2 7
3 6
4 5
75 207 390 974
Hint
In the sample, the shape of the generalized segment tree is the same as the example in the statement.
After the first modification, becomes , so the new . We can compute:
- $M_2 = a_1 \times a_2 \times a_3 = 2 \times 2 \times 3 = 12$
- $M_1 = a_1 \times a_2 \times a_3 \times a_4 = 2 \times 2 \times 3 \times 4 = 48$
So the sum of weights is .
After the second modification, becomes . The remaining operations are similar to the first one, so they are not repeated here.
Translated by ChatGPT 5