Suma de nivel máximo en el árbol N-ario

Dado un árbol N-ario que consta de Nodes valorados [1, N] y un valor de array [] , donde cada Node i está asociado con valor [i] , la tarea es encontrar la suma máxima de todos los valores de Node de todos los niveles del Árbol N-ario .

Ejemplos:

Entrada: N = 8, Bordes[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, Valor[] = {4, 2, 3, -5, -1, 3, -2, 6}
Salida: 6
Explicación:
La suma de todos los Nodes del nivel 0 es 4 La
suma de todos los Nodes del 1er nivel es 0
La suma de todos los Nodes del 3er nivel es 0. 
La suma de todos los Nodes del 4to nivel es 6. 
Por lo tanto, la suma máxima de cualquier nivel del árbol es 6.

Entrada: N = 10, Bordes[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}, Valor[] = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}
Salida: 25

Enfoque: este problema se puede resolver utilizando el orden transversal de nivel . Mientras realiza el recorrido, procese los Nodes de diferentes niveles por separado. Para cada nivel que se procesa, calcule la suma de Nodes en ese nivel y realice un seguimiento de la suma máxima. Sigue los pasos:

  1. Almacene todos los Nodes secundarios en el nivel actual en la cola y luego cuente la suma total de Nodes en el nivel actual después de que se complete el recorrido del orden de niveles para un nivel en particular.
  2. Dado que la cola ahora contiene todos los Nodes del siguiente nivel, la suma total de Nodes en el siguiente nivel se puede calcular fácilmente recorriendo la cola.
  3. Siga el mismo procedimiento para los niveles sucesivos y actualice la suma máxima de Nodes encontrados en cada nivel.
  4. Después de los pasos anteriores, imprima la suma máxima de valores almacenados.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
int maxLevelSum(int N, int M,
                vector<int> Value,
                int Edges[][2])
{
    // Stores the edges of the graph
    vector<int> adj[N];
 
    // Create Adjacency list
    for (int i = 0; i < M; i++) {
        adj[Edges[i][0]].push_back(
            Edges[i][1]);
    }
 
    // Initialize result
    int result = Value[0];
 
    // Stores the nodes of each level
    queue<int> q;
 
    // Insert root
    q.push(0);
 
    // Perform level order traversal
    while (!q.empty()) {
 
        // Count of nodes of the
        // current level
        int count = q.size();
 
        int sum = 0;
 
        // Traverse the current level
        while (count--) {
 
            // Dequeue a node from queue
            int temp = q.front();
            q.pop();
 
            // Update sum of current level
            sum = sum + Value[temp];
 
            // Enqueue the children of
            // dequeued node
            for (int i = 0;
                 i < adj[temp].size(); i++) {
                q.push(adj[temp][i]);
            }
        }
 
        // Update maximum level sum
        result = max(sum, result);
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    // Number of nodes
    int N = 10;
 
    // Edges of the N-ary tree
    int Edges[][2] = { { 0, 1 }, { 0, 2 },
                       { 0, 3 }, { 1, 4 },
                       { 1, 5 }, { 3, 6 },
                       { 6, 7 }, { 6, 8 },
                       { 6, 9 } };
    // Given cost
    vector<int> Value = { 1, 2, -1, 3, 4,
                          5, 8, 6, 12, 7 };
 
    // Function call
    cout << maxLevelSum(N, N - 1,
                        Value, Edges);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG{
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
@SuppressWarnings("unchecked")
static int maxLevelSum(int N, int M, int[] Value,
                                     int Edges[][])
{
     
    // Stores the edges of the graph
    ArrayList<Integer>[] adj = new ArrayList[N];
 
    for(int i = 0; i < N; i++)
    {
        adj[i] = new ArrayList<>();
    }
 
    // Create Adjacency list
    for(int i = 0; i < M; i++)
    {
        adj[Edges[i][0]].add(Edges[i][1]);
    }
 
    // Initialize result
    int result = Value[0];
 
    // Stores the nodes of each level
    Queue<Integer> q = new LinkedList<>();
 
    // Insert root
    q.add(0);
 
    // Perform level order traversal
    while (!q.isEmpty())
    {
         
        // Count of nodes of the
        // current level
        int count = q.size();
 
        int sum = 0;
 
        // Traverse the current level
        while (count-- > 0)
        {
             
            // Dequeue a node from queue
            int temp = q.poll();
 
            // Update sum of current level
            sum = sum + Value[temp];
 
            // Enqueue the children of
            // dequeued node
            for(int i = 0; i < adj[temp].size(); i++)
            {
                q.add(adj[temp].get(i));
            }
        }
 
        // Update maximum level sum
        result = Math.max(sum, result);
    }
 
    // Return the result
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Number of nodes
    int N = 10;
 
    // Edges of the N-ary tree
    int[][] Edges = { { 0, 1 }, { 0, 2 },
                      { 0, 3 }, { 1, 4 },
                      { 1, 5 }, { 3, 6 },
                      { 6, 7 }, { 6, 8 },
                      { 6, 9 } };
    // Given cost
    int[] Value = { 1, 2, -1, 3, 4,
                    5, 8, 6, 12, 7 };
 
    // Function call
    System.out.println(maxLevelSum(N, N - 1,
                                   Value, Edges));
}
}
 
// This code is contributed by sanjeev2552

Python3

# Python3 program for the above approach
from collections import deque
 
# Function to find the maximum sum
# a level in N-ary treeusing BFS
def maxLevelSum(N, M, Value, Edges):
     
    # Stores the edges of the graph
    adj = [[] for i in range(N)]
 
    # Create Adjacency list
    for i in range(M):
        adj[Edges[i][0]].append(Edges[i][1])
 
    # Initialize result
    result = Value[0]
 
    # Stores the nodes of each level
    q = deque()
 
    # Insert root
    q.append(0)
 
    # Perform level order traversal
    while (len(q) > 0):
 
        # Count of nodes of the
        # current level
        count = len(q)
 
        sum = 0
 
        # Traverse the current level
        while (count):
 
            # Dequeue a node from queue
            temp = q.popleft()
 
            # Update sum of current level
            sum = sum + Value[temp]
 
            # Enqueue the children of
            # dequeued node
            for i in range(len(adj[temp])):
                q.append(adj[temp][i])
                 
            count -= 1
 
        # Update maximum level sum
        result = max(sum, result)
 
    # Return the result
    return result
 
# Driver Code
if __name__ == '__main__':
     
    # Number of nodes
    N = 10
 
    # Edges of the N-ary tree
    Edges = [ [ 0, 1 ], [ 0, 2 ],
              [ 0, 3 ], [ 1, 4 ],
              [ 1, 5 ], [ 3, 6 ],
              [ 6, 7 ], [ 6, 8 ],
              [ 6, 9 ] ]
               
    # Given cost
    Value = [ 1, 2, -1, 3, 4,
              5, 8, 6, 12, 7 ]
 
    # Function call
    print(maxLevelSum(N, N - 1,
                      Value, Edges))
 
# This code is contributed by mohit kumar 29

C#

// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
 
static int maxLevelSum(int N, int M,
                       int[] Value,
                       int [,]Edges)
{
  // Stores the edges of the graph
  List<int>[] adj = new List<int>[N];
 
  for(int i = 0; i < N; i++)
  {
    adj[i] = new List<int>();
  }
 
  // Create Adjacency list
  for(int i = 0; i < M; i++)
  {
    adj[Edges[i, 0]].Add(Edges[i, 1]);
  }
 
  // Initialize result
  int result = Value[0];
 
  // Stores the nodes of each level
  Queue<int> q = new Queue<int>();
 
  // Insert root
  q.Enqueue(0);
 
  // Perform level order
  // traversal
  while (q.Count != 0)
  {
    // Count of nodes of the
    // current level
    int count = q.Count;
 
    int sum = 0;
 
    // Traverse the current
    // level
    while (count-- > 0)
    {
      // Dequeue a node from
      // queue
      int temp = q.Peek();
      q.Dequeue();
 
      // Update sum of current
      // level
      sum = sum + Value[temp];
 
      // Enqueue the children of
      // dequeued node
      for(int i = 0;
              i < adj[temp].Count; i++)
      {
        q.Enqueue(adj[temp][i]);
      }
    }
 
    // Update maximum level sum
    result = Math.Max(sum, result);
  }
 
  // Return the result
  return result;
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Number of nodes
  int N = 10;
 
  // Edges of the N-ary tree
  int[,] Edges = {{0, 1}, {0, 2},
                  {0, 3}, {1, 4},
                  {1, 5}, {3, 6},
                  {6, 7}, {6, 8},
                  {6, 9}};
  // Given cost
  int[] Value = {1, 2, -1, 3, 4,
                 5, 8, 6, 12, 7};
 
  // Function call
  Console.WriteLine(maxLevelSum(N, N - 1,
                                Value, Edges));
}
}
 
// This code is contributed by Princi Singh

Javascript

<script>
 
    // JavaScript program for the above approach
     
    // Function to find the maximum sum
    // a level in N-ary treeusing BFS
 
    function maxLevelSum(N, M, Value, Edges)
    {
      // Stores the edges of the graph
      let adj = new Array(N);
 
      for(let i = 0; i < N; i++)
      {
        adj[i] = [];
      }
 
      // Create Adjacency list
      for(let i = 0; i < M; i++)
      {
        adj[Edges[i][0]].push(Edges[i][1]);
      }
 
      // Initialize result
      let result = Value[0];
 
      // Stores the nodes of each level
      let q = [];
 
      // Insert root
      q.push(0);
 
      // Perform level order
      // traversal
      while (q.length != 0)
      {
        // Count of nodes of the
        // current level
        let count = q.length;
 
        let sum = 0;
 
        // Traverse the current
        // level
        while (count-- > 0)
        {
          // Dequeue a node from
          // queue
          let temp = q[0];
          q.shift();
 
          // Update sum of current
          // level
          sum = sum + Value[temp];
 
          // Enqueue the children of
          // dequeued node
          for(let i = 0; i < adj[temp].length; i++)
          {
            q.push(adj[temp][i]);
          }
        }
 
        // Update maximum level sum
        result = Math.max(sum, result);
      }
 
      // Return the result
      return result;
    }
     
    // Number of nodes
    let N = 10;
 
    // Edges of the N-ary tree
    let Edges = [[0, 1], [0, 2],
                    [0, 3], [1, 4],
                    [1, 5], [3, 6],
                    [6, 7], [6, 8],
                    [6, 9]];
    // Given cost
    let Value = [1, 2, -1, 3, 4, 5, 8, 6, 12, 7];
 
    // Function call
    document.write(maxLevelSum(N, N - 1, Value, Edges));
 
</script>
Producción

25

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por muskan_garg y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *