You are given a rooted tree with nodes numbered from
to
, where node
is the root. The tree has
edges, and for each node
(where
), there is an edge of length
connecting it to its parent
.
Define as the length of the longest simple path in the subtree rooted at node
that passes through node
.
Your task is to compute the sum of for all nodes modulo
, i.e.
.
Moreover, there are updates. In each update, you are given two integers
and
, meaning the edge between node
and its parent
increases its length by
x
. After each update, output the new sum modulo .
Input Specification
The first line contains an integer (
), the number of nodes.
The second line contains integers
,
,
,
, (
), the parent of each node
(for
).
The second line contains integers
,
,
,
, (
), the initial edge length between node
and
.
The fourth line contains an integer (
), the number of update operations.
The next lines each contain two integers
and
, (
,
), representing an update: increase the weight of the edge between
and
by
.
Output Specification
Output lines. The first line should contain the initial sum of
modulo
, and then print
lines, each with the new sum modulo
after the corresponding update.
Constraints
Subtask | Points | Additional constraints |
---|---|---|
Tree's height is at most | ||
All | ||
No additional constraints |
Sample Input
5
0 0 1 1
0 0 0 0
10
1 2
2 2
3 2
4 2
4 1
3 1
2 1
1 1
4 1000
2 1000
Sample Output
0
2
4
8
10
12
13
14
15
2015
3015
Explanation for Sample
Initial tree:
0
/ \
1 2
/ \
3 4
- Initially,
.
- After the first update,
. The sum is
.
- After the second update,
. The sum is
.
- After the third update,
and
. The sum is
.
- After the fourth update,
and
. The sum is
.
Comments