Open In App

Minimum value of root node

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer X, a tree of N nodes rooted at node 0 and an array P[] of size N, such that P[i] = Parent of node i (P[0] = -1). Assign non-negative values to all the nodes such that the value of the parent node >= sum of immediate child nodes and the sum of all nodes >= X. Find the minimum value that needs to be assigned to the tree’s root.

Examples:

Input: N = 4, X = 7, P = [-1, 0, 1, 2]
Output: 2
Explanation: The minimum value of root is 2.

Binary-Tree

Input: N = 4, X = 10, P = [-1, 0, 1, 0]
Output: 4
Explanation: The minimum value of root is 4.

Binary-Tree-(1)

Approach: This can be solved with the following idea:

We can solve this problem by calculating the maximum depth of a node in the tree. Let’s say there is a node A which has the maximum depth D, then it means we can distribute X equally over all the nodes from root to node A and if we are left with some remainder we can add 1 to the elements which are at the top. So, the minimum value of the root node can be ceil(X/(D + 1)).

Below are the steps involved:

  • Construct the graph using array P[].
  • Run a DFS to find the maximum depth D of any node.
  • Calculate the value ceil(X / (D+1)) and return it.

Below is the implementation of the code:

C++




// C++ Code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// DFS Method to fint the maximum depth
void dfs(vector<int>* adj, int& D, int node, int depth)
{
    D = max(D, depth);
    for (auto child : adj[node]) {
        dfs(adj, D, child, depth + 1);
    }
}
 
// Function to find minimum value for root
int optimalValue(int N, int X, vector<int>& P)
{
    vector<int> adj[N];
 
    // Construct the graph
    for (int node = 1; node < N; node++) {
        int par = P[node];
        adj[par].push_back(node);
    }
    int D = 0;
 
    // DFS to find the maximum depth
    dfs(adj, D, 0, 0);
 
    // Return the minimum value of root
    return ceil(X / (1.0 * (D + 1)));
}
 
// Driver code
int main()
{
 
    int N = 4;
    int X = 7;
    vector<int> P = { -1, 0, 1, 2 };
 
    // Function call
    cout << optimalValue(N, X, P);
 
    return 0;
}


Java




// Java Code for the above approach
import java.util.ArrayList;
import java.util.List;
 
class GFG {
    // DFS Method to fint the maximum depth
    public static void dfs(List<Integer>[] adj, int[] D, int node, int depth) {
        D[0] = Math.max(D[0], depth);
        for (int child : adj[node]) {
            dfs(adj, D, child, depth + 1);
        }
    }
 
    // Function to find minimum value for root
    public static int optimalValue(int N, int X, List<Integer> P) {
        List<Integer>[] adj = new List[N];
 
        for (int i = 0; i < N; i++) {
            adj[i] = new ArrayList<>();
        }
         
        // Construct the graph
        for (int node = 1; node < N; node++) {
            int par = P.get(node);
            adj[par].add(node);
        }
        int[] D = new int[1];
         
        // DFS to find the maximum depth
        dfs(adj, D, 0, 0);
         
        // Return the minimum value of root
        return (int) Math.ceil(X / (1.0 * (D[0] + 1)));
    }
     
    // Driver code
    public static void main(String[] args) {
        int N = 4;
        int X = 7;
        List<Integer> P = new ArrayList<>();
        P.add(-1);
        P.add(0);
        P.add(1);
        P.add(2);
         
        // Function call
        System.out.println(optimalValue(N, X, P));
    }
}


Python3




# DFS method to find the maximum depth
def dfs(adj, D, node, depth):
    D[0] = max(D[0], depth)
    for child in adj[node]:
        dfs(adj, D, child, depth + 1)
 
# Function to find minimum value for root
def optimal_value(N, X, P):
    adj = [[] for _ in range(N)]
 
    # Construct the graph
    for node in range(1, N):
        par = P[node]
        adj[par].append(node)
    D = [0]
 
    # DFS to find the maximum depth
    dfs(adj, D, 0, 0)
 
    # Return the minimum value of root
    return (X // (D[0] + 1)) + (X % (D[0] + 1) > 0)
 
# Driver code
N = 4
X = 7
P = [-1, 0, 1, 2]
 
# Function call
print(optimal_value(N, X, P))


C#




// C# Implementation:
using System;
using System.Collections.Generic;
 
class Program
{
    // DFS Method to find the maximum depth
    public static void Dfs(List<int>[] adj, int[] D, int node, int depth)
    {
        D[0] = Math.Max(D[0], depth);
        foreach (int child in adj[node])
        {
            Dfs(adj, D, child, depth + 1);
        }
    }
 
    // Function to find minimum value for root
    public static int OptimalValue(int N, int X, List<int> P)
    {
        List<int>[] adj = new List<int>[N];
 
        for (int i = 0; i < N; i++)
        {
            adj[i] = new List<int>();
        }
 
        // Construct the graph
        for (int node = 1; node < N; node++)
        {
            int par = P[node];
            adj[par].Add(node);
        }
        int[] D = new int[1];
 
        // DFS to find the maximum depth
        Dfs(adj, D, 0, 0);
 
        // Return the minimum value of root
        return (int)Math.Ceiling(X / (1.0 * (D[0] + 1)));
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int N = 4;
        int X = 7;
        List<int> P = new List<int> { -1, 0, 1, 1 };
 
        // Function call
        Console.WriteLine(OptimalValue(N, X, P));
    }
}
// This code is contributed by Tapesh(tapeshdua420)


Javascript




function GFG(adj, D, node, depth) {
    // Update the maximum depth (D[0])
    // if the current depth is greater.
    D[0] = Math.max(D[0], depth);
    for (let child of adj[node]) {
        GFG(adj, D, child, depth + 1);
    }
}
// Function to calculate the minimum value for
// the root node.
function optimalValue(N, X, P) {
    const adj = Array.from({ length: N }, () => []);
 
    // Build the tree by populating the adjacency list based on
    // the parent-child relationships.
    for (let node = 1; node < N; node++) {
        const par = P[node];
        adj[par].push(node);
    }
    // Initialize an array to store the maximum depth.
    const D = [0];
    GFG(adj, D, 0, 0);
    return Math.ceil(X / (D[0] + 1));
}
// Input values
const N = 4;
const X = 7;
const P = [-1, 0, 1, 2];
// Call the optimalValue function to
// find the result.
const result = optimalValue(N, X, P);
// Output the result.
console.log(result);


Output

2





Time Complexity: O(N), where N is the number of nodes in the graph
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads