📜  N元树可能包含的子树数

📅  最后修改于: 2021-04-18 02:36:30             🧑  作者: Mango

给定一棵由N个节点组成的N元树,其值从0(N – 1) ,则任务是查找给定树中存在的子树总数。由于计数可能非常大,因此打印计数模为1000000007。

例子:

方法:解决给定问题的方法是在给定树上执行DFS遍历。请按照以下步骤解决问题:

  • 初始化一个变量,例如count0 ,以存储给定树中存在的子树总数的计数。
  • 声明一个函数DFS(int src,int parent)以计算节点src的子树数量,并执行以下操作:
    • 初始化变量,例如res1
    • 遍历当前节点的邻接列表,如果邻接列表中的该节点说X节点不同,则递归调用该节点X的DFS函数和作为节点的节点src作为DFS(X, src)
    • 让返回到上述递归调用的值为value ,然后将res的值更新为(res *(value + 1))%(10 9 + 7)
    • count的值更新为(count + res)%(10 9 + 7)
    • 从每个递归调用返回res的值。
  • 为根节点1调用函数DFS()
  • 完成上述步骤后,打印count的值作为结果。

下面是上述方法的实现:

C++
// C++ program of the above approach
 
#include 
#define MAX 300004
using namespace std;
 
// Adjacency list to
// represent the graph
vector graph[MAX];
int mod = 1e9 + 7;
 
// Stores the count of subtrees
// possible from given N-ary Tree
int ans = 0;
 
// Utility function to count the number of
// subtrees possible from given N-ary Tree
int countSubtreesUtil(int cur, int par)
{
    // Stores the count of subtrees
    // when cur node is the root
    int res = 1;
 
    // Traverse the adjacency list
    for (int i = 0;
         i < graph[cur].size(); i++) {
 
        // Iterate over every ancestor
        int v = graph[cur][i];
 
        if (v == par)
            continue;
 
        // Calculate product of the number
        // of subtrees for each child node
        res = (res
               * (countSubtreesUtil(
                      v, cur)
                  + 1))
              % mod;
    }
 
    // Update the value of ans
    ans = (ans + res) % mod;
 
    // Return the resultant count
    return res;
}
 
// Function to count the number of
// subtrees in the given tree
void countSubtrees(int N,
                   vector >& adj)
{
    // Initialize an adjacency matrix
    for (int i = 0; i < N - 1; i++) {
        int a = adj[i].first;
        int b = adj[i].second;
 
        // Add the edges
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
 
    // Function Call to count the
    // number of subtrees possible
    countSubtreesUtil(1, 1);
 
    // Print count of subtrees
    cout << ans + 1;
}
 
// Driver Code
int main()
{
    int N = 3;
 
    vector > adj
        = { { 0, 1 }, { 1, 2 } };
 
    countSubtrees(N, adj);
 
    return 0;
}


Java
// Java program of above approach
import java.util.*;
 
class GFG{
     
static int MAX = 300004;
 
// Adjacency list to
// represent the graph
static ArrayList> graph;
static long mod = (long)1e9 + 7;
  
// Stores the count of subtrees
// possible from given N-ary Tree
static int ans = 0;
  
// Utility function to count the number of
// subtrees possible from given N-ary Tree
static int countSubtreesUtil(int cur, int par)
{
     
    // Stores the count of subtrees
    // when cur node is the root
    int res = 1;
  
    // Traverse the adjacency list
    for(int i = 0;
            i < graph.get(cur).size(); i++)
    {
  
        // Iterate over every ancestor
        int v = graph.get(cur).get(i);
  
        if (v == par)
            continue;
  
        // Calculate product of the number
        // of subtrees for each child node
        res = (int)((res * (countSubtreesUtil(
                 v, cur) + 1)) % mod);
    }
  
    // Update the value of ans
    ans = (int)((ans + res) % mod);
  
    // Return the resultant count
    return res;
}
  
// Function to count the number of
// subtrees in the given tree
static void countSubtrees(int N, int[][] adj)
{
     
    // Initialize an adjacency matrix
    for(int i = 0; i < N - 1; i++)
    {
        int a = adj[i][0];
        int b = adj[i][1];
  
        // Add the edges
        graph.get(a).add(b);
        graph.get(b).add(a);
    }
  
    // Function Call to count the
    // number of subtrees possible
    countSubtreesUtil(1, 1);
  
    // Print count of subtrees
   System.out.println(ans + 1);
}
 
// Driver code
public static void main(String[] args)
{
    int N = 3;
     
    int[][] adj = { { 0, 1 }, { 1, 2 } };
     
    graph = new ArrayList<>();
     
    for(int i = 0; i < MAX; i++)
        graph.add(new ArrayList<>());
     
    countSubtrees(N, adj);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program of the above approach
MAX = 300004
 
# Adjacency list to
# represent the graph
graph = [[] for i in range(MAX)]
mod = 10**9 + 7
 
# Stores the count of subtrees
# possible from given N-ary Tree
ans = 0
 
# Utility function to count the number of
# subtrees possible from given N-ary Tree
def countSubtreesUtil(cur, par):
    global mod, ans
     
    # Stores the count of subtrees
    # when cur node is the root
    res = 1
 
    # Traverse the adjacency list
    for i in range(len(graph[cur])):
 
        # Iterate over every ancestor
        v = graph[cur][i]
 
        if (v == par):
            continue
 
        # Calculate product of the number
        # of subtrees for each child node
        res = (res * (countSubtreesUtil(v, cur)+ 1)) % mod
 
    # Update the value of ans
    ans = (ans + res) % mod
 
    # Return the resultant count
    return res
 
# Function to count the number of
# subtrees in the given tree
def countSubtrees(N, adj):
   
    # Initialize an adjacency matrix
    for i in range(N-1):
        a = adj[i][0]
        b = adj[i][1]
 
        # Add the edges
        graph[a].append(b)
        graph[b].append(a)
 
    # Function Call to count the
    # number of subtrees possible
    countSubtreesUtil(1, 1)
 
    # Prcount of subtrees
    print (ans + 1)
 
# Driver Code
if __name__ == '__main__':
    N = 3
 
    adj = [ [ 0, 1 ], [ 1, 2 ] ]
 
    countSubtrees(N, adj)
 
# This code is contributed by mohit kumar 29.


输出:
7

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