Maximum Depth Path SumMedium

Maximum Depth Path Sum

MediumPractice library · +20 XPtreesdynamic programmingdepth first search

Given a rooted tree where each node has a value, find the maximum sum of values along any root-to-leaf path. The tree is represented by a parent array, where parent[i] is the parent of node i, and parent[0] is -1, indicating that node 0 is the root. Node values are given in a separate array.

Input

The first line contains an integer N (1 <= N <= 200000), the number of nodes. The second line contains N integers, parent, where parent[i] is the parent of node i. parent[0] is -1. The third line contains N integers, values, where values[i] is the value of node i.

Output

Print a single integer, the maximum sum of values along any root-to-leaf path.

Constraints

1 <= N <= 200000 -10^9 <= values[i] <= 10^9

Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests

Example 1

Input
5
-1 0 0 1 1
10 2 -5 3 7
Output
19

Root is 0 with value 10. Paths are 0->1->3 (10+2+3=15), 0->1->4 (10+2+7=19), 0->2 (10-5=5). Max is 19.

Example 2

Input
3
-1 0 0
-1 -2 -3
Output
-3

All values are negative. Paths are 0->1 (-1-2=-3), 0->2 (-1-3=-4). Max is -3.

Hints