Interest degree of vertices
Practice
1.7 (19 votes)
Basic programming
Basics of implementation
Implementation
Problem
91% Success 3713 Attempts 30 Points 5s Time Limit 256MB Memory 1024 KB Max Code

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

  1. First line: \(n\)
  2. 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
  3. 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

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
57 votes
Tags:
Ad-HocEasyMathOpen
Points:30
25 votes
Tags:
Basic ProgrammingBasics of ImplementationBit ManipulationImplementationPermutation and combination
Points:30
16 votes
Tags:
Basic ProgrammingBasics of ImplementationEasyImplementation