📌  相关文章
📜  最大化 N 叉树中每个节点的 MEX 值的总和

📅  最后修改于: 2021-09-06 05:57:52             🧑  作者: Mango

给定一棵 N 叉树 1为根,任务是以任何顺序将[0, N – 1]范围内的值分配给每个节点,以使树中每个节点的 MEX 值总和最大化并打印MEX值的最大可能总和树中的每个节点。

例子:

方法:想法是对给定的 N 叉树执行 DFS 遍历,并找到树中每个子树的MEX和。请按照以下步骤解决问题:

  • 对以节点 1 为根的树执行深度优先搜索(DFS)。
  • 0初始化变量mex ,用1初始化大小
  • 遍历当前节点的所有子节点并执行以下操作:
    • 递归调用当前节点的子节点,并将所有子树中 MEX 的最大和存储在mex 中
    • 增加以当前节点为根的树的大小。
  • 按大小增加mex的值。
  • 完成以上步骤后,打印mex的值作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to create an N-ary Tree
void makeTree(vector tree[],
              pair edges[],
              int N)
{
    // Traverse the edges
    for (int i = 0; i < N - 1; i++) {
 
        int u = edges[i].first;
        int v = edges[i].second;
 
        // Add edges
        tree[u].push_back(v);
    }
}
 
// Function to get the maximum sum
// of MEX values of tree rooted at 1
pair dfs(int node,
                   vector tree[])
{
    // Initialize mex
    int mex = 0;
 
    int size = 1;
 
    // Iterate through all children
    // of node
    for (int u : tree[node]) {
 
        // Recursively find maximum sum
        // of MEX values of each node
        // in tree rooted at u
        pair temp = dfs(u, tree);
 
        // Store the maximum sum of MEX
        // of among all subtrees
        mex = max(mex, temp.first);
 
        // Increase the size of tree
        // rooted at current node
        size += temp.second;
    }
 
    // Resulting MEX for the current
    // node of the recursive call
    return { mex + size, size };
}
 
// Driver Code
int main()
{
    // Given N nodes
    int N = 7;
 
    // Given N-1 edges
    pair edges[]
        = { { 1, 4 }, { 1, 5 }, { 5, 2 }, { 5, 3 }, { 4, 7 }, { 7, 6 } };
 
    // Stores the tree
    vector tree[N + 1];
 
    // Generates the tree
    makeTree(tree, edges, N);
 
    // Returns maximum sum of MEX
    // values of each node
    cout << dfs(1, tree).first;
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
static class pair
{
    int first, second;
     
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to create an N-ary Tree
static void makeTree(Vector tree[],
                     pair edges[], int N)
{
     
    // Traverse the edges
    for(int i = 0; i < N - 1; i++)
    {
        int u = edges[i].first;
        int v = edges[i].second;
         
        // Add edges
        tree[u].add(v);
    }
}
 
// Function to get the maximum sum
// of MEX values of tree rooted at 1
static pair dfs(int node, Vector tree[])
{
     
    // Initialize mex
    int mex = 0;
 
    int size = 1;
 
    // Iterate through all children
    // of node
    for(int u : tree[node])
    {
         
        // Recursively find maximum sum
        // of MEX values of each node
        // in tree rooted at u
        pair temp = dfs(u, tree);
         
        // Store the maximum sum of MEX
        // of among all subtrees
        mex = Math.max(mex, temp.first);
         
        // Increase the size of tree
        // rooted at current node
        size += temp.second;
    }
     
    // Resulting MEX for the current
    // node of the recursive call
    return new pair(mex + size, size);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given N nodes
    int N = 7;
 
    // Given N-1 edges
    pair edges[] = { new pair(1, 4),
                     new pair(1, 5),
                     new pair(5, 2),
                     new pair(5, 3),
                     new pair(4, 7),
                     new pair(7, 6) };
 
    // Stores the tree
    @SuppressWarnings("unchecked")
    Vector[] tree = new Vector[N + 1];
    for(int i = 0; i < tree.length; i++)
        tree[i] = new Vector();
         
    // Generates the tree
    makeTree(tree, edges, N);
 
    // Returns maximum sum of MEX
    // values of each node
    System.out.print((dfs(1, tree).first));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above approach
 
# Function to create an N-ary Tree
def makeTree(tree, edges, N):
     
    # Traverse the edges
    for i in range(N - 1):
        u = edges[i][0]
        v = edges[i][1]
 
        # Add edges
        tree[u].append(v)
         
    return tree
 
# Function to get the maximum sum
# of MEX values of tree rooted at 1
def dfs(node, tree):
     
    # Initialize mex
    mex = 0
 
    size = 1
 
    # Iterate through all children
    # of node
    for u in tree[node]:
 
        # Recursively find maximum sum
        # of MEX values of each node
        # in tree rooted at u
        temp = dfs(u, tree)
 
        # Store the maximum sum of MEX
        # of among all subtrees
        mex = max(mex, temp[0])
 
        # Increase the size of tree
        # rooted at current node
        size += temp[1]
 
    # Resulting MEX for the current
    # node of the recursive call
    return [mex + size, size]
 
# Driver Code
if __name__ == '__main__':
     
    # Given N nodes
    N = 7
 
    # Given N-1 edges
    edges = [ [ 1, 4 ], [ 1, 5 ],
              [ 5, 2 ], [ 5, 3 ],
              [ 4, 7 ], [ 7, 6 ] ]
 
    # Stores the tree
    tree = [[] for i in range(N + 1)]
 
    # Generates the tree
    tree = makeTree(tree, edges, N)
 
    # Returns maximum sum of MEX
    # values of each node
    print(dfs(1, tree)[0])
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
public class pair
{
    public int first, second;
     
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to create an N-ary Tree
static void makeTree(List []tree,
                     pair []edges, int N)
{
     
    // Traverse the edges
    for(int i = 0; i < N - 1; i++)
    {
        int u = edges[i].first;
        int v = edges[i].second;
         
        // Add edges
        tree[u].Add(v);
    }
}
 
// Function to get the maximum sum
// of MEX values of tree rooted at 1
static pair dfs(int node, List []tree)
{
     
    // Initialize mex
    int mex = 0;
     
    int size = 1;
     
    // Iterate through all children
    // of node
    foreach(int u in tree[node])
    {
         
        // Recursively find maximum sum
        // of MEX values of each node
        // in tree rooted at u
        pair temp = dfs(u, tree);
         
        // Store the maximum sum of MEX
        // of among all subtrees
        mex = Math.Max(mex, temp.first);
         
        // Increase the size of tree
        // rooted at current node
        size += temp.second;
    }
     
    // Resulting MEX for the current
    // node of the recursive call
    return new pair(mex + size, size);
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given N nodes
    int N = 7;
     
    // Given N-1 edges
    pair []edges = { new pair(1, 4),
                     new pair(1, 5),
                     new pair(5, 2),
                     new pair(5, 3),
                     new pair(4, 7),
                     new pair(7, 6) };
 
    // Stores the tree
    List[] tree = new List[N + 1];
    for(int i = 0; i < tree.Length; i++)
        tree[i] = new List();
         
    // Generates the tree
    makeTree(tree, edges, N);
     
    // Returns maximum sum of MEX
    // values of each node
    Console.Write((dfs(1, tree).first));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
13

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live