📜  找到加权和最小的子树的根

📅  最后修改于: 2021-10-25 03:09:48             🧑  作者: Mango

给定一棵树,以及所有节点的权重,任务是找到加权和最小的子树的根。

例子:

方法:对树进行dfs,对每一个节点计算以当前节点为根的子树加权和,然后找到一个节点的最小和值。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
int ans = 0, mini = INT_MAX;
 
vector graph[100];
vector weight(100);
 
// Function to perform dfs and update the tree
// such that every node's weight is the sum of
// the weights of all the nodes in the sub-tree
// of the current node including itself
void dfs(int node, int parent)
{
    for (int to : graph[node]) {
        if (to == parent)
            continue;
        dfs(to, node);
 
        // Calculating the weighted
        // sum of the subtree
        weight[node] += weight[to];
    }
}
 
// Function to find the node
// having minimum sub-tree sum
void findMin(int n)
{
 
    // For every node
    for (int i = 1; i <= n; i++) {
 
        // If current node's weight
        // is minimum so far
        if (mini > weight[i]) {
            mini = weight[i];
            ans = i;
        }
    }
}
 
// Driver code
int main()
{
    int n = 5;
 
    // Weights of the node
    weight[1] = -1;
    weight[2] = 5;
    weight[3] = -1;
    weight[4] = 3;
    weight[5] = -2;
 
    // Edges of the tree
    graph[1].push_back(2);
    graph[2].push_back(3);
    graph[2].push_back(4);
    graph[1].push_back(5);
 
    dfs(1, 1);
    findMin(n);
 
    cout << ans;
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
    static int ans = 0, mini = Integer.MAX_VALUE;
     
    @SuppressWarnings("unchecked")
    static Vector[] graph = new Vector[100];
    static Integer[] weight = new Integer[100];
 
    // Function to perform dfs and update the tree
    // such that every node's weight is the sum of
    // the weights of all the nodes in the sub-tree
    // of the current node including itself
    static void dfs(int node, int parent)
    {
        for (int to : graph[node])
        {
            if (to == parent)
                continue;
            dfs(to, node);
 
            // Calculating the weighted
            // sum of the subtree
            weight[node] += weight[to];
        }
    }
 
    // Function to find the node
    // having minimum sub-tree sum  x
    static void findMin(int n)
    {
 
        // For every node
        for (int i = 1; i <= n; i++)
        {
 
            // If current node's weight  x
            // is minimum so far
            if (mini > weight[i])
            {
                mini = weight[i];
                ans = i;
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
         
        int n = 5;
        for (int i = 0; i < 100; i++)
            graph[i] = new Vector();
         
        // Weights of the node
        weight[1] = -1;
        weight[2] = 5;
        weight[3] = -1;
        weight[4] = 3;
        weight[5] = -2;
 
        // Edges of the tree
        graph[1].add(2);
        graph[2].add(3);
        graph[2].add(4);
        graph[1].add(5);
 
        dfs(1, 1);
        findMin(n);
 
        System.out.print(ans);
    }
}
 
// This code is contributed by shubhamsingh10


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    static int ans = 0, mini = int.MaxValue;
 
    static List[] graph = new List[100];
    static int[] weight = new int[100];
  
    // Function to perform dfs and update the tree
    // such that every node's weight is the sum of
    // the weights of all the nodes in the sub-tree
    // of the current node including itself
    static void dfs(int node, int parent)
    {
        foreach (int to in graph[node])
        {
            if (to == parent)
                continue;
            dfs(to, node);
  
            // Calculating the weighted
            // sum of the subtree
            weight[node] += weight[to];
        }
    }
  
    // Function to find the node
    // having minimum sub-tree sum  x
    static void findMin(int n)
    {
  
        // For every node
        for (int i = 1; i <= n; i++)
        {
  
            // If current node's weight  x
            // is minimum so far
            if (mini > weight[i])
            {
                mini = weight[i];
                ans = i;
            }
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
          
        int n = 5;
        for (int i = 0; i < 100; i++)
            graph[i] = new List();
          
        // Weights of the node
        weight[1] = -1;
        weight[2] = 5;
        weight[3] = -1;
        weight[4] = 3;
        weight[5] = -2;
  
        // Edges of the tree
        graph[1].Add(2);
        graph[2].Add(3);
        graph[2].Add(4);
        graph[1].Add(5);
  
        dfs(1, 1);
        findMin(n);
  
        Console.Write(ans);
    }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
ans = 0
mini = 2**32
 
graph = [[] for i in range(100)]
weight = [0]*100
 
# Function to perform dfs and update the tree
# such that every node's weight is the sum of
# the weights of all the nodes in the sub-tree
# of the current node including itself
def dfs(node, parent):
    global mini, graph, weight, ans
    for to in graph[node]:
        if (to == parent):
            continue
        dfs(to, node)
         
        # Calculating the weighted
        # sum of the subtree
        weight[node] += weight[to]
     
# Function to find the node
# having minimum sub-tree sum
def findMin(n):
    global mini, graph, weight, ans
     
    # For every node
    for i in range(1, n + 1):
         
        # If current node's weight
        # is minimum so far
        if (mini > weight[i]):
            mini = weight[i]
            ans = i
 
# Driver code
n = 5
 
# Weights of the node
weight[1] = -1
weight[2] = 5
weight[3] = -1
weight[4] = 3
weight[5] = -2
 
# Edges of the tree
graph[1].append(2)
graph[2].append(3)
graph[2].append(4)
graph[1].append(5)
 
dfs(1, 1)
findMin(n)
 
print(ans)
 
# This code is contributed by SHUBHAMSINGH10


Javascript


输出:
5

复杂度分析:

  • 时间复杂度: O(N)。
    在 dfs 中,树的每个节点都被处理一次,因此如果树中总共有 N 个节点,则由于 dfs 的复杂性是 O(N)。因此,时间复杂度为 O(N)。
  • 辅助空间: O(n)。
    递归堆栈。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程