Pretty Painting

Time limit: 0.5s Memory limit: 256MB Input: Output:

Valerio is drawing his (rooted) Christmas tree to celebrate his favorite holiday. Being a computer scientist, his tree has NN nodes, numbered from 00 to N1N-1, with node 00 being the root. Each other node is connected to its parent PiP_i by an edge of length WiW_i.

Details of Valerio’s tree..\text{Details of Valerio's tree.}.

Task

Valerio now wants to color some of the edges to make his drawing look more similar to the original subject. He also wants to avoid making the drawing too chaotic, therefore each node ii can have at most KiK_i incident colored edges. What is the maximum total length of colored edges he can achieve?

Input data

The input file consists of:

  • a line containing integer NN.
  • a line containing the NN integers K0,,KN1K_{0}, \, \ldots, \, K_{N-1}.
  • a line containing the N1\mathtt{N - 1} integers P1,,PN1P_{1}, \, \ldots, \, P_{N-1}.
  • a line containing the N1\mathtt{N - 1} 64-bit integers W1,,WN1W_{1}, \, \ldots, \, W_{N-1}.

Output data

The output file must contain a single line consisting of 64-bit integer ans\mathtt{ans}.

Constraints and clarifications

  • 1N100 0001 \le N \le 100 \ 000.
  • 0Ki<N0 \le K_i < N for each i=0N1i=0\ldots N-1.
  • 0Pi<i0 \le P_i < i for each i=1N1i=1\ldots N-1.
  • 0Wi1 000 000 0000 \le W_i \le 1 \ 000 \ 000 \ 000 for each i=1N1i=1\ldots N-1.
# Score Constraints
1 0 Examples
2 12 N20N \le 20, Wi100W_i \le 100 for each i=1N1i=1\ldots N-1
3 24 Pi=i1P_i = i - 1 for each i=1N1i = 1\ldots N-1
4 33 N1 000N \le 1 \ 000
5 31 No additional restrictions

Example 1

stdin

5
1 1 1 1 1
0 0 1 1
4 2 3 5

stdout

7

Explanation

The tree in the first sample case is depicted below.

The optimal solution consists in coloring the edge between nodes 00 and 22 and the one between nodes 11 and 44, as shown below, with a total length of 77.

Example 2

stdin

7
1 2 2 1 1 1 1
0 0 1 1 2 2
8 7 6 6 3 4

stdout

23

Explanation

In the second sample case, the optimal solution consists in coloring the edges (0,2)(0,2), (1,3)(1,3), (1,4)(1,4) and (2,6)(2,6), for a total length of 2323.

Log in or sign up to be able to send submissions!