Sum in the tree

Practice this coding question on Coding Gurukul.

Problem statement

A tree-shaped irrigation network records the total water added along each route from its root. Every junction contributes a nonnegative integer amount. A damaged report has lost all route totals at even depths, while totals at odd depths remain readable. The engineer wants a consistent repair that uses the smallest total amount across all junctions. Your task Assign a nonnegative integer a[v] to every vertex. For each recorded s[v], the sum of a values on the root-to-v path, including both endpoints, must equal s[v]. Minimize the sum of a[v] over all vertices, or report that no assignment exists. Important details Vertex 1 is the root at depth 1. Exactly the even-depth totals are marked -1. Zero contributions are allowed. Each parent index is smaller than its child index. A path total cannot decrease when moving from a parent to a child. Print the minimum total, not a repaired tree. Worked example For parents 1 2 2 and totals 2 -1 5 7, the tree has root 1, child 2, and two grandchildren. Choosing the missing total as 5 gives contributions 2, 3, 0 and 2, whose sum is 7. Choosing 2 instead would cost 10. If a known grandchild total is below the root total, no repair is possible.

Input format

First line: n. Second line: parents p[2] through p[n]. Third line: n path totals, using -1 for erased totals.

Output format

Print the minimum sum of contributions, or -1 if impossible.

Constraints

2 <= n <= 1000; 1 <= p[i] < i; odd-depth totals are between 0 and 1000000000; even-depth totals are -1. Use 64-bit sums.

Sample input

4
1 2 2
2 -1 5 7

Sample output

7

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…