Loading [MathJax]/jax/output/CommonHTML/jax.js


Dynamic Diameter 2

Description

You are given an edge-weighted tree of size N where vertices are numbered from 0 to N1. 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.

Input

The first line contains a single integer N, the number of vertices in the tree.

The second line contains N1 integers p1,p2,,pN1.

The third line contains N1 integers d1,d2,,dN1.

The fourth line contains Q, the number of updates.

The following Q lines contains two integers vi and addi.

Output

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.

Constraints

  • 2N100 000
  • 1Q100 000
  • 1di100 000 000
  • 0pi<i
  • 1vi<N
  • 1addi1 000 000 000

Subtasks

  • 1N1 000, 1Q1 000 (11 points)
  • The height of the tree is at most 50 (13 points)
  • di=100 000 000, addi=1 (31 points)
  • No additional constraints (45 points)

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


Submitting to 'Dynamic Diameter 2'


You're not logged in! Click here to login


Submitting to 'Dynamic Diameter 2'


You're not logged in! Click here to login


Submitting .cpp to 'Dynamic Diameter 2'


You're not logged in! Click here to login

Time Limit: 5 Seconds
Memory Limit: 1024MB
Your best score: 0
Source: RMI 2020
Editorial: 1

Subtask Score
1 11
2 13
3 31
4 45
5 0