📌  相关文章
📜  具有N个顶点的树的可能数量

📅  最后修改于: 2021-05-04 22:59:50             🧑  作者: Mango

给定N个正整数的数组arr [] 。任务是找到可能具有N个顶点的树的数量,以使顶点1和顶点i之间的距离为arr [i] 。这样的树的总数可能非常大,因此以10 9 + 7为模返回答案。

例子:

天真的方法:以下是步骤:

  1. 如果A 1 != 0且来自A 2的元素。 。 。 N0,那么将无法生成树,因此在这种情况下,树的数量为0
  2. 如果我们将第一个节点作为根节点,则级别1上的所有节点必须是根节点的子节点,级别2上的所有节点必须是1个级别节点的子节点,因此只有一种可能性将它们放置在级别-明智的。
  3. 现在令x是节点的数量上i电平,y为对节点的数(i + 1)电平,以便对水平布置的节点的可能性的数量i和第(i + 1)是x和y。
  4. 因此,树木的计数将是X I X(I + 1),其中X i是节点的数量在i电平

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
const int mod = 1e9 + 7;
  
// Function to count the total number
// of trees possible
int NumberOfTrees(int arr[], int N)
{
    // Find the max element in the
    // given array
    int maxElement = *max_element(arr, arr + N);
  
    // Level array store the number of
    // nodes on level i initially all
    // values are zero
    int level[maxElement + 1] = { 0 };
    for (int i = 0; i < N; i++) {
  
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1) {
  
        return 0;
    }
  
    // To store the count of trees
    int ans = 1;
  
    // Iterate until maxElement
    for (int i = 0; i < maxElement; i++) {
  
        // Calculate level[i]^level[i+1]
        for (int j = 0; j < level[i + 1]; j++) {
  
            // Update the count of tree
            ans = (ans * level[i]) % mod;
        }
    }
  
    // Return the final count of trees
    return ans;
}
  
// Driver Code
int main()
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function Call
    cout << NumberOfTrees(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
  
class GFG{
      
static int mod = (int)(1e9 + 7);
  
// Function to count the total number
// of trees possible
static int NumberOfTrees(int arr[], int N)
{
      
    // Find the max element in the
    // given array
    int maxElement = Arrays.stream(arr).max().getAsInt();
  
    // Level array store the number of
    // nodes on level i initially all
    // values are zero
    int level[] = new int[maxElement + 1];
    for(int i = 0; i < N; i++) 
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
  
    // To store the count of trees
    int ans = 1;
  
    // Iterate until maxElement
    for(int i = 0; i < maxElement; i++)
    {
          
        // Calculate level[i]^level[i+1]
        for (int j = 0; j < level[i + 1]; j++)
        {
              
            // Update the count of tree
            ans = (ans * level[i]) % mod;
        }
    }
  
    // Return the final count of trees
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    System.out.print(NumberOfTrees(arr, N));
}
}
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
mod = int(1e9 + 7)
  
# Function to count the total number
# of trees possible
def NumberOfTrees(arr, N):
      
    # Find the max element in the
    # given array
    maxElement = max(arr);
  
    # Level array store the number of
    # Nodes on level i initially all
    # values are zero
    level = [0] * (maxElement + 1);
    for i in range(N):
        level[arr[i]] += 1;
  
    # In this case tree can not be created
    if (arr[0] != 0 or level[0] != 1):
        return 0;
  
    # To store the count of trees
    ans = 1;
  
    # Iterate until maxElement
    for i in range(maxElement):
  
        # Calculate level[i]^level[i+1]
        for j in range(level[i + 1]):
              
            # Update the count of tree
            ans = (ans * level[i]) % mod;
  
    # Return the final count of trees
    return ans;
  
# Driver Code
if __name__ == '__main__':
      
    N = 7;
  
    # Given array arr
    arr = [ 0, 3, 2, 1, 2, 2, 1 ];
  
    # Function call
    print(NumberOfTrees(arr, N));
  
# This code is contributed by shikhasingrajput


C#
// C# program for the above approach
using System;
using System.Linq;
class GFG{
      
static int mod = (int)(1e9 + 7);
  
// Function to count the total number
// of trees possible
static int NumberOfTrees(int []arr, int N)
{
      
    // Find the max element in the
    // given array
    int maxElement = arr.Max();
  
    // Level array store the number of
    // nodes on level i initially all
    // values are zero
    int []level = new int[maxElement + 1];
    for(int i = 0; i < N; i++) 
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
  
    // To store the count of trees
    int ans = 1;
  
    // Iterate until maxElement
    for(int i = 0; i < maxElement; i++)
    {
          
        // Calculate level[i]^level[i+1]
        for (int j = 0; j < level[i + 1]; j++)
        {
              
            // Update the count of tree
            ans = (ans * level[i]) % mod;
        }
    }
  
    // Return the readonly count of trees
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 7;
  
    // Given array []arr
    int []arr = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    Console.Write(NumberOfTrees(arr, N));
}
}
  
// This code is contributed by gauravrajput1


C++
// C++ program for the above approach
#include 
using namespace std;
const int mod = 1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
int power(int x, int y)
{
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if (y & 1)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
int NumberOfTrees(int arr[], int N)
{
  
    // Find the max element in array
    int maxElement
        = *max_element(arr, arr + N);
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int level[maxElement + 1] = { 0 };
  
    for (int i = 0; i < N; i++) {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1) {
  
        return 0;
    }
  
    int ans = 1;
  
    for (int i = 0; i < maxElement; i++) {
  
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1]))
              % mod;
    }
  
    // Return the final count
    return ans;
}
  
// Driver Code
int main()
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function Call
    cout << NumberOfTrees(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
  
class GFG{
      
static int mod = (int)1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
static int power(int x, int y)
{
      
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if ((y & 1) != 0)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
static int NumberOfTrees(int arr[], int N)
{
  
    // Find the max element in array
    int maxElement = Arrays.stream(arr).max().getAsInt();
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int []level = new int[maxElement + 1];
  
    for(int i = 0; i < N; i++)
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
      
    int ans = 1;
  
    for(int i = 0; i < maxElement; i++) 
    {
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod;
    }
  
    // Return the final count
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    System.out.print(NumberOfTrees(arr, N));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach 
mod = int(1e9 + 7)
  
# Function that finds the value of x^y
# using Modular Exponentiation
def power(x, y):
  
    # Base Case
    if(y == 0):
        return 1
  
    p = power(x, y // 2) % mod
  
    p = (p * p) % mod
  
    # If y is odd, multiply
    # x with result
    if(y & 1):
        p = (x * p) % mod
  
    # Return the value
    return p
  
# Function that counts the total
# number of trees possible
def NumberOfTrees(arr, N):
  
    # Find the max element in array
    maxElement = max(arr)
  
    # Level array store the number nodes
    # on level i initially all values are 0
    level = [0] * (maxElement + 1)
  
    for i in range(N):
        level[arr[i]] += 1
  
    # In this case tree can not be created
    if(arr[0] != 0 or level[0] != 1):
        return 0
  
    ans = 1
  
    for i in range(maxElement):
  
        # Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod
  
    # Return the final count
    return ans
  
# Driver Code
N = 7
  
# Given Queries
arr = [ 0, 3, 2, 1, 2, 2, 1 ]
  
# Function call
print(NumberOfTrees(arr, N))
  
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
using System.Linq;
  
class GFG{
      
static int mod = (int)1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
static int power(int x, int y)
{
      
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if ((y & 1) != 0)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
static int NumberOfTrees(int []arr, int N)
{
  
    // Find the max element in array
    int maxElement = arr.Max();
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int []level = new int[maxElement + 1];
  
    for(int i = 0; i < N; i++)
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
      
    int ans = 1;
  
    for(int i = 0; i < maxElement; i++) 
    {
          
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod;
    }
  
    // Return the readonly count
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 7;
  
    // Given array []arr
    int []arr = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    Console.Write(NumberOfTrees(arr, N));
}
} 
  
// This code is contributed by 29AjayKumar


输出:
24

时间复杂度: O(N * K),其中K是级别中的顶点数。
辅助空间: O(N)

高效方法:可以通过使用模幂优化(ans * level [i])的值来优化上述方法。步骤如下:

  1. 如果指数是奇数,则将其减去1,然后将基数乘以答案即可。
  2. 如果指数为偶数,则将指数除以2,然后将底数平方。
  3. 指数变为0时返回1。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
const int mod = 1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
int power(int x, int y)
{
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if (y & 1)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
int NumberOfTrees(int arr[], int N)
{
  
    // Find the max element in array
    int maxElement
        = *max_element(arr, arr + N);
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int level[maxElement + 1] = { 0 };
  
    for (int i = 0; i < N; i++) {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1) {
  
        return 0;
    }
  
    int ans = 1;
  
    for (int i = 0; i < maxElement; i++) {
  
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1]))
              % mod;
    }
  
    // Return the final count
    return ans;
}
  
// Driver Code
int main()
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function Call
    cout << NumberOfTrees(arr, N);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
  
class GFG{
      
static int mod = (int)1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
static int power(int x, int y)
{
      
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if ((y & 1) != 0)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
static int NumberOfTrees(int arr[], int N)
{
  
    // Find the max element in array
    int maxElement = Arrays.stream(arr).max().getAsInt();
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int []level = new int[maxElement + 1];
  
    for(int i = 0; i < N; i++)
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
      
    int ans = 1;
  
    for(int i = 0; i < maxElement; i++) 
    {
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod;
    }
  
    // Return the final count
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 7;
  
    // Given array arr[]
    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    System.out.print(NumberOfTrees(arr, N));
}
}
  
// This code is contributed by 29AjayKumar 

Python3

# Python3 program for the above approach 
mod = int(1e9 + 7)
  
# Function that finds the value of x^y
# using Modular Exponentiation
def power(x, y):
  
    # Base Case
    if(y == 0):
        return 1
  
    p = power(x, y // 2) % mod
  
    p = (p * p) % mod
  
    # If y is odd, multiply
    # x with result
    if(y & 1):
        p = (x * p) % mod
  
    # Return the value
    return p
  
# Function that counts the total
# number of trees possible
def NumberOfTrees(arr, N):
  
    # Find the max element in array
    maxElement = max(arr)
  
    # Level array store the number nodes
    # on level i initially all values are 0
    level = [0] * (maxElement + 1)
  
    for i in range(N):
        level[arr[i]] += 1
  
    # In this case tree can not be created
    if(arr[0] != 0 or level[0] != 1):
        return 0
  
    ans = 1
  
    for i in range(maxElement):
  
        # Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod
  
    # Return the final count
    return ans
  
# Driver Code
N = 7
  
# Given Queries
arr = [ 0, 3, 2, 1, 2, 2, 1 ]
  
# Function call
print(NumberOfTrees(arr, N))
  
# This code is contributed by Shivam Singh

C#

// C# program for the above approach
using System;
using System.Linq;
  
class GFG{
      
static int mod = (int)1e9 + 7;
  
// Function that finds the value of x^y
// using Modular Exponentiation
static int power(int x, int y)
{
      
    // Base Case
    if (y == 0)
        return 1;
  
    int p = power(x, y / 2) % mod;
  
    p = (p * p) % mod;
  
    // If y is odd, multiply
    // x with result
    if ((y & 1) != 0)
        p = (x * p) % mod;
  
    // Return the value
    return p;
}
  
// Function that counts the total
// number of trees possible
static int NumberOfTrees(int []arr, int N)
{
  
    // Find the max element in array
    int maxElement = arr.Max();
  
    // Level array store the number nodes
    // on level i initially all values are 0
    int []level = new int[maxElement + 1];
  
    for(int i = 0; i < N; i++)
    {
        level[arr[i]]++;
    }
  
    // In this case tree can not be created
    if (arr[0] != 0 || level[0] != 1)
    {
        return 0;
    }
      
    int ans = 1;
  
    for(int i = 0; i < maxElement; i++) 
    {
          
        // Calculate level[i]^level[i+1]
        ans = (ans * power(level[i],
                           level[i + 1])) % mod;
    }
  
    // Return the readonly count
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 7;
  
    // Given array []arr
    int []arr = { 0, 3, 2, 1, 2, 2, 1 };
  
    // Function call
    Console.Write(NumberOfTrees(arr, N));
}
} 
  
// This code is contributed by 29AjayKumar
输出:
24

时间复杂度: O(N * log K),其中K是级别中的顶点数。
辅助空间: O(N)