CSES - Aalto Competitive Programming 2024 - wk6 - Mon - Tree game
  • Time limit: 1.50 s
  • Memory limit: 1024 MB

Maija and Uolevi are playing a game on a rooted tree. The tree has n vertices numbered 1,2,\dots,n. The i-th vertex has a_i points on it and it's parent is p_i. Vertex 1 is the root and it is it's own parent. At the beginning of the game there is a piece on the root and the players start making moves in order:

  1. If possible, Maija cuts one of the edges that is connected to the vertex that currently has the piece and leads away from the root.

  2. Uolevi collects the points from the current vertex and moves the piece away from the root along an edge that has not been cut. If there are no such edges then the game ends.

Maija tries to minimize the total number of points Uolevi collects while Uolevi seeks to maximize it. Find the final score if both players play optimally.

Input

The first line contains a single integer n. The second line contains n integers a_1,\,a_2,\ldots,\,a_n. The third line contains n integers p_1,\,p_2,\ldots,\,p_n.

Output

Print the final score

Constraints

  • 1 \leq n \leq 10^5
  • 1 \leq a_i \leq 10^9
  • 1 \leq p_i \leq n

Example 1

Input:

5
10 5 1 7 4 
1 1 5 3 1

Output:

14

Explanation:

1.1 Maija cuts the edge between nodes 1 and 2.
1.2 Uolevi collects 10 points from node 1 and moves the piece to node 5.
2.1 Maija cuts the edge between nodes 5 and 3
2.2 Uolevi collects the points from node 5 and the game ends.

Example 2

Input:

10
5 6 4 5 7 9 5 8 8 4 
1 1 4 2 6 1 6 5 1 1

Output:

13