#K82012. Maximum Root-to-Leaf Path Sum

    ID: 35881 Type: Default 1000ms 256MiB

Maximum Root-to-Leaf Path Sum

Maximum Root-to-Leaf Path Sum

You are given a rooted tree with n nodes. Each node is assigned an integer value. The tree is represented by two arrays: one for node values and another for the parent indices of each node. The root node is denoted by a parent index of -1. Your task is to find the maximum sum along any path from the root to a leaf.

More formally, if the value of node i is \(a_i\), and a valid root-to-leaf path is represented as \(v_0, v_1, \ldots, v_k\) (with \(v_0\) being the root and \(v_k\) a leaf), then you must compute:

[ \max_{\text{leaf } v_k} \left{ \sum_{j=0}^{k} a_{v_j} \right} ]

The tree is 0-indexed, and it is guaranteed that the input represents a valid tree.

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains a single integer \(T\) representing the number of test cases.
  2. For each test case:
    • The first line contains an integer \(n\) representing the number of nodes in the tree.
    • The second line contains \(n\) space-separated integers representing the values of the nodes.
    • The third line contains \(n\) space-separated integers where the \(i\)th integer is the parent index of node \(i\) (with -1 indicating the root).

outputFormat

For each test case, print a single line to standard output (stdout) containing one integer — the maximum sum obtainable from a path from the root to any leaf in the given tree.

## sample
2
5
1 -2 3 4 -1
-1 0 0 2 2
3
1 2 3
-1 0 1
8

6

</p>