📌  相关文章
📜  N元树中任何两个级别的总和之间的最大绝对差

📅  最后修改于: 2021-05-04 19:02:36             🧑  作者: Mango

给定一棵具有由N个节点组成的正负值且(N – 1)个边的N元树,任务是在其中找到级别总和的最大绝对差。

例子:

方法:要找到水平总和的最大绝对差,先找到最高水平之和最小级别总和,因为最高水平之最小级别总和的绝对差值总是给我们最大绝对差值即

步骤如下:

  1. 在给定的N元树上执行BFS遍历。
  2. 在进行BFS遍历时,请分别处理不同级别的节点。
  3. 对于每个要处理的级别,请计算级别中节点的总和,并跟踪最大和最小级别总和。
  4. 经过上述遍历后,找出最大和最小电平总和的绝对差。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum
// absolute difference of level sum
void maxAbsDiffLevelSum(int N, int M,
                        vector cost,
                        int Edges[][2])
{
    // Create the adjacency list
    vector adj[N];
 
    for (int i = 0; i < M; i++) {
        int u = Edges[i][0];
        int v = Edges[i][1];
        adj[u].push_back(v);
    }
 
    // Initialize value of maximum
    // and minimum level sum
    int maxSum = cost[0], minSum = cost[0];
 
    // Do Level order traversal keeping
    // track of nodes at every level
    queue q;
    q.push(0);
 
    while (!q.empty()) {
 
        // Get the size of queue when
        // the level order traversal
        // for one level finishes
        int count = q.size();
 
        int sum = 0;
 
        // Iterate for all the nodes
        // in the queue currently
        while (count--) {
 
            // Dequeue an node from queue
            int temp = q.front();
            q.pop();
 
            sum = sum + cost[temp];
 
            // Enqueue the children of
            // dequeued node
            for (int i = 0;
                 i < adj[temp].size(); i++) {
 
                q.push(adj[temp][i]);
            }
        }
 
        // Update the maximum level
        // sum value
        maxSum = max(sum, maxSum);
 
        // Update the minimum level
        // sum value
        minSum = min(sum, minSum);
    }
 
    // Return the result
    cout << abs(maxSum - minSum);
}
 
// Driver Code
int main()
{
    // Number of nodes and edges
    int N = 10, M = 9;
 
    // 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 cost = { 1, 2, -1, 3, 4,
                         5, 8, 6, 12, 7 };
 
    // Function Call
    maxAbsDiffLevelSum(N, M, cost, Edges);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum
// absolute difference of level sum
static void maxAbsDiffLevelSum(int N, int M,
                               int []cost,
                               int Edges[][])
{
     
    // Create the adjacency list
    @SuppressWarnings("unchecked")
    Vector []adj = new Vector[N];
    for(int i = 0; i < adj.length; i++)
        adj[i] = new Vector();
         
    for(int i = 0; i < M; i++)
    {
        int u = Edges[i][0];
        int v = Edges[i][1];
        adj[u].add(v);
    }
 
    // Initialize value of maximum
    // and minimum level sum
    int maxSum = cost[0], minSum = cost[0];
 
    // Do Level order traversal keeping
    // track of nodes at every level
    Queue q = new LinkedList();
    q.add(0);
 
    while (!q.isEmpty())
    {
         
        // Get the size of queue when
        // the level order traversal
        // for one level finishes
        int count = q.size();
 
        int sum = 0;
 
        // Iterate for all the nodes
        // in the queue currently
        while (count-- > 0)
        {
 
            // Dequeue an node from queue
            int temp = q.peek();
            q.remove();
 
            sum = sum + cost[temp];
 
            // Enqueue the children of
            // dequeued node
            for(int i = 0;
                    i < adj[temp].size();
                    i++)
            {
                q.add(adj[temp].get(i));
            }
        }
 
        // Update the maximum level
        // sum value
        maxSum = Math.max(sum, maxSum);
 
        // Update the minimum level
        // sum value
        minSum = Math.min(sum, minSum);
    }
 
    // Return the result
    System.out.print(Math.abs(maxSum - minSum));
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Number of nodes and edges
    int N = 10, M = 9;
 
    // 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 []cost = { 1, 2, -1, 3, 4,
                   5, 8, 6, 12, 7 };
 
    // Function call
    maxAbsDiffLevelSum(N, M, cost, Edges);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
from collections import deque
 
# Function to find the maximum
# absolute difference of level sum
def maxAbsDiffLevelSum(N, M, cost, Edges):
 
    # Create the adjacency list
    adj = [[] for i in range(N)]
 
    for i in range(M):
        u = Edges[i][0]
        v = Edges[i][1]
        adj[u].append(v)
 
    # Initialize value of maximum
    # and minimum level sum
    maxSum = cost[0]
    minSum = cost[0]
 
    # Do Level order traversal keeping
    # track of nodes at every level
    q = deque()
    q.append(0)
 
    while len(q) > 0:
 
        # Get the size of queue when
        # the level order traversal
        # for one level finishes
        count = len(q)
 
        sum = 0
 
        # Iterate for all the nodes
        # in the queue currently
        while (count):
 
            # Dequeue an node from queue
            temp = q.popleft()
            # q.pop()
 
            sum = sum + cost[temp]
 
            # Enqueue the children of
            # dequeued node
            for i in adj[temp]:
                q.append(i)
                 
            count -= 1
 
        # Update the maximum level
        # sum value
        maxSum = max(sum, maxSum)
 
        # Update the minimum level
        # sum value
        minSum = min(sum, minSum)
 
    # Return the result
    print(abs(maxSum - minSum))
 
# Driver Code
if __name__ == '__main__':
     
    # Number of nodes and edges
    N = 10
    M = 9
 
    # 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
    cost = [ 1, 2, -1, 3, 4,
             5, 8, 6, 12, 7 ]
 
    # Function call
    maxAbsDiffLevelSum(N, M, cost, 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
// absolute difference of level sum
static void maxAbsDiffLevelSum(int N, int M,
                               int []cost,
                               int [,]Edges)
{
  // Create the adjacency list
  List []adj = new List[N];
  for(int i = 0; i < adj.Length; i++)
    adj[i] = new List();
 
  for(int i = 0; i < M; i++)
  {
    int u = Edges[i, 0];
    int v = Edges[i, 1];
    adj[u].Add(v);
  }
 
  // Initialize value of maximum
  // and minimum level sum
  int maxSum = cost[0], minSum = cost[0];
 
  // Do Level order traversal keeping
  // track of nodes at every level
  Queue q = new Queue();
  q.Enqueue(0);
 
  while (q.Count!=0)
  {
    // Get the size of queue when
    // the level order traversal
    // for one level finishes
    int count = q.Count;
 
    int sum = 0;
 
    // Iterate for all the nodes
    // in the queue currently
    while (count-- > 0)
    {
      // Dequeue an node from queue
      int temp = q.Peek();
      q.Dequeue();
 
      sum = sum + cost[temp];
 
      // Enqueue the children of
      // dequeued node
      for(int i = 0; i < adj[temp].Count; i++)
      {
        q.Enqueue(adj[temp][i]);
      }
    }
 
    // Update the maximum level
    // sum value
    maxSum = Math.Max(sum, maxSum);
 
    // Update the minimum level
    // sum value
    minSum = Math.Min(sum, minSum);
  }
 
  // Return the result
  Console.Write(Math.Abs(maxSum - minSum));
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Number of nodes and edges
  int N = 10, M = 9;
 
  // 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 []cost = {1, 2, -1, 3, 4,
                5, 8, 6, 12, 7};
 
  // Function call
  maxAbsDiffLevelSum(N, M, cost, Edges);
}
}
 
// This code is contributed by 29AjayKumar


输出:
24



时间复杂度: O(N)
辅助空间: O(N)