📜  N-ary 树中可能的子树计数

📅  最后修改于: 2021-10-25 03:31:05             🧑  作者: Mango

给定一个由N 个节点组成的N叉树,其值为0(N – 1) ,任务是找到给定树中存在的子树总数。由于计数可能非常大,所以打印计数模 1000000007。

例子:

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

  • 初始化一个变量,比如count0 ,以存储给定树中存在的子树总数的计数。
  • 声明一个函数DFS(int src, int parent)来统计节点src的子树数,并执行以下操作:
    • 初始化一个变量,比如res1
    • 遍历当前节点的邻接表,如果邻接表中的节点,说X节点不一样,则递归调用节点X的DFS函数和作为节点的节点srcDFS(X,源)
    • 让上述递归调用返回的值为 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.


C#
// C# program of above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
    static int MAX = 300004;
 
    // Adjacency list to
    // represent the graph
    static List> 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[cur].Count; 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 = (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[a].Add(b);
            graph[b].Add(a);
        }
 
        // Function Call to count the
        // number of subtrees possible
        countSubtreesUtil(1, 1);
 
        // Print count of subtrees
        Console.WriteLine(ans + 1);
    }
 
    // Driver code
    public static void Main(String[] args) {
        int N = 3;
 
        int[,] adj = { { 0, 1 }, { 1, 2 } };
 
        graph = new List>();
 
         
for (int i = 0; i < MAX; i++)
            graph.Add(new List());
        countSubtrees(N, adj);
    }
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
7

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

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