You are given a rooted tree with \(n\) vertices. There is a number written on each leaf (a vertex contains degree 1 and the root node can be a leaf if it has just one child). The interest degree of each vertex is the sum of numbers written on leaves in subtree on this vertex. In each step, you can change the number written on a leaf by 1. How many steps are required to make the interest degree of all of the nodes equal?
Note: You can change the number written on a leaf to negative values.
Input format
- First line: \(n\)
- Next line: \(n-1\) numbers where the \(i^{th}\) number is \(p_i\) denoting the parent of \((i + 1)^{th}\) node
Note: Node 1 is the root - Third line: \(n\) numbers where the \(i^{th}\) of them is \(a_i\) denoting the number that is written on vertex \(i\).
Note: It is guaranteed that if \(i\) is not a leaf, then \(a_i = 0\).
Output format
Print the minimum number of steps that are required to make the interest degree of all of the nodes equal.
Constraints
\(1 \le n \le 10^5\\ 1 \le p_i < i\\ 0 \le a_i \le 10^9\)
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor
Login to unlock the editorial