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

📅  最后修改于: 2021-06-25 10:51:32             🧑  作者: 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]范围内,另一个循环直到从1到可能的最大得分2 *(N – 1) ,并且每个[ s ,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


输出
8

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