📌  相关文章
📜  根据给定条件构造二叉树可以获得的最大可能分数

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

给定一个由(N – 1) 个整数组成的数组arr[] ,每个值arr[i] (基于 1 的索引)是度数为i的节点的分数。任务是确定可以构造的任何N 个节点的树的最大分数。

例子:

朴素方法:最简单的方法是生成构建具有N 个节点的树的所有可能组合,并找到每个节点的总分。然后,打印获得的所有分数的最大值。

时间复杂度: (N!)其中 N 是树中的节点数。
辅助空间: O(N)

高效方法:为了优化上述方法,想法是通过创建一个dp[][]表来使用动态规划,其中dp[i][j]表示使用i 个节点的最大分数,节点的度数总和为j .请按照以下步骤解决问题:

  • 初始化数组dp[N + 1][2*(N – 1) + 1]其中N是节点数, (2*(N – 1))是最大度数总和。
  • 0初始化dp[0][0]
  • 迭代两个嵌套循环,一个在范围[1, N] 上,另一个 for 直到可能的最大分数2*(N – 1) from 1并且对于范围[1, N]中的每个分数s遍历给定的数组给arr[]评分并将dp[i][s]更新为:
  • 对于具有N个顶点和(N – 1) 条边的树,所有度的总和应该是2 * (N – 1) 。因此,打印dp[N][2*(N – 1)] 的值作为具有N 个节点的树的最大分数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum score
// for one possible tree having N nodes
// N - 1 Edges
int maxScore(vector& arr)
{
    int N = arr.size();
 
    // Number of nodes
    N++;
 
    // Initialize dp[][]
    vector >
        dp(N + 1, vector(2 * N,
                              -100000));
 
    // Score with 0 vertices is 0
    dp[0][0] = 0;
 
    // Traverse the nodes from 1 to N
    for (int i = 1; i <= N; i++) {
 
        // Find maximum scores for
        // each sum
        for (int s = 1;
             s <= 2 * (N - 1); s++) {
 
            // Iterate over degree of
            // new node
            for (int j = 1; j <= N - 1
                            and j <= s;
                 j++) {
 
                // Update the current
                // state
                dp[i][s]
                    = max(dp[i][s],
                          arr[j - 1]
                              + dp[i - 1][s - j]);
            }
        }
    }
 
    // Return maximum score for N node
    // tree having 2(N - 1) sum of degree
    return dp[N][2 * (N - 1)];
}
 
// Driver Code
int main()
{
    // Given array of scores
    vector arr = { 1, 3, 0 };
 
    // Function Call
    cout << maxScore(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum score
// for one possible tree having N nodes
// N - 1 Edges
static int maxScore(int[] arr)
{
    int N = arr.length;
 
    // Number of nodes
    N++;
 
    // Initialize dp[][]
    int [][] dp = new int[N + 1][2 * (N - 1) + 1];
     
    // Score with 0 vertices is 0
    dp[0][0] = 0;
 
    // Traverse the nodes from 1 to N
    for(int i = 1; i <= N; i++)
    {
         
        // Find maximum scores for
        // each sum
        for(int s = 1; s <= 2 * (N - 1); s++)
        {
             
            // Iterate over degree of
            // new node
            for(int j = 1; j <= N - 1 && j <= s; j++)
            {
                 
                // Update the current
                // state
                dp[i][s] = Math.max(dp[i][s],
                                   arr[j - 1] +
                                    dp[i - 1][s - j]);
            }
        }
    }
 
    // Return maximum score for N node
    // tree having 2(N - 1) sum of degree
    return dp[N][2 * (N - 1)] - 1;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array of scores
    int [] arr = { 1, 3, 0 };
 
    // Function Call
    System.out.print(maxScore(arr));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to find the maximum score
# for one possible tree having N nodes
# N - 1 Edges
def maxScore(arr):
     
    N = len(arr)
 
    # Number of nodes
    N += 1
 
    # Initialize dp[][]
    dp = [[-100000 for i in range(2 * N)]
                   for i in range(N + 1)]
 
    # Score with 0 vertices is 0
    dp[0][0] = 0
 
    # Traverse the nodes from 1 to N
    for i in range(1, N + 1):
         
        # Find maximum scores for
        # each sum
        for s in range(1, 2 * (N - 1) + 1):
             
            # Iterate over degree of
            # new node
            j = 1
            while j <= N - 1 and j <= s:
                 
                # Update the current
                # state
                dp[i][s] = max(dp[i][s], arr[j - 1] +
                               dp[i - 1][s - j])
                j += 1
                 
    # Return maximum score for N node
    # tree having 2(N - 1) sum of degree
    return dp[N][2 * (N - 1)]
 
# Driver Code
if __name__ == '__main__':
     
    # Given array of scores
    arr = [ 1, 3, 0 ]
 
    # Function Call
    print(maxScore(arr))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
class GFG{
 
// Function to find the
// maximum score for one
// possible tree having N
// nodes N - 1 Edges
static int maxScore(int[] arr)
{
  int N = arr.Length;
 
  // Number of nodes
  N++;
 
  // Initialize [,]dp
  int [,] dp = new int[N + 1,
                       2 * (N -
                       1) + 1];
 
  // Score with 0 vertices
  // is 0
  dp[0, 0] = 0;
 
  // Traverse the nodes from
  // 1 to N
  for(int i = 1; i <= N; i++)
  {
    // Find maximum scores for
    // each sum
    for(int s = 1;
            s <= 2 * (N - 1); s++)
    {
      // Iterate over degree of
      // new node
      for(int j = 1;
              j <= N - 1 && j <= s; j++)
      {
        // Update the current
        // state
        dp[i, s] = Math.Max(dp[i, s],
                            arr[j - 1] +
                            dp[i - 1,
                               s - j]);
      }
    }
  }
 
  // Return maximum score for
  // N node tree having 2(N - 1)
  // sum of degree
  return dp[N, 2 * (N -
            1)] - 1;
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Given array of scores
  int [] arr = {1, 3, 0};
 
  // Function Call
  Console.Write(maxScore(arr));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出
8

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

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