You are given an edge-weighted tree of size N where vertices are numbered from 0 to N−1. The tree is rooted at vertex 0. Vertex i is connected to vertex pi with an edge of length di.
For each vertex i, let li denote the length of the longest path such that vertex i is contained in the path and all vertices used are contained in the subtree of i. Recall a path is a sequence of vertices a1,a2,…,ak such that all a are distinct and ai and ai+1 is connected by an edge. Your job is to find ∑ni=1li.
Since this problem is not hard enough to be a December Course problem 5, we are going to make Q modifications to the tree. In the i-th modification you will be given vi and addi. You should increase the edge connecting vertex vi and pvi by addi. Note that updates are persistent, modifications made to the tree will apply when processing futures modifications.
Also because ∑ni=1li is very big, you should find the answer modulo 109+7.
The first line contains a single integer N, the number of vertices in the tree.
The second line contains N−1 integers p1,p2,…,pN−1.
The third line contains N−1 integers d1,d2,…,dN−1.
The fourth line contains Q, the number of updates.
The following Q lines contains two integers vi and addi.
You should output Q+1 lines. The first line should contain the answer before any updates are made. On the i+1th line you should print the answer after the ith modification.
All answers must be printed modulo 109+7.
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
0
2
4
8
10
12
13
14
15
2015
3015
Subtask | Score |
---|---|
1 | 11 |
2 | 13 |
3 | 31 |
4 | 45 |
5 | 0 |