Given a tree consisting of N nodes numbered from [1, N] and is colored either black(denoted by 1) or green(denoted by 0), the task is to count the number of sequences of length K [a1, a2, ..aK] such that the path taken between consecutive nodes is the shortest one and the edges covered consist of at least one black edge. Since the answer can be large, print it to modulo of 109+7.
Input: N = 4, K = 4
1-2 0
2-3 0
2-4 0
Output: 0
Explanation:
Since there is no black edge in the tree. There are no such sequences.Input: N = 3, K = 3
1-2 1
2-3 1
Output: 24
Explanation:
All the 33 sequences except for (1, 1, 1), (2, 2, 2) and (3, 3, 3) are included in the answer.
Approach:
The idea is to count the number of sequences of length K such that no black edge is covered. Let the count be temp. Then (NK) – temp is the required answer. temp can be easily calculated by removing the black edges and then calculating the size of different components of the resultant graph.
Follow the steps below:
- Initialize the value of ans as NK.
- Construct a graph G by adding only green edges.
- Perform a DFS traversal of the graph and keep subtracting (sizeK) from the ans where size is the number of nodes in different components of the graph G.
Below is the implementation of the above approach:
C++
// C++ implementation of the// above approach#include <bits/stdc++.h>#define int long long intusing namespace std;const int mod = 1e9 + 7;const int N = 1e5 + 1;// Vector to store the graphvector<int> G[N];// Iterative Function to calculate// (a<sup>b</sup>) % mod in O(log b)int power(int a, int b) { // Initialize result int res = 1; // Update x if it is more than // or equal to p a = a % mod; if (a == 0) // In case x is divisible by p; return 0; while (b > 0) { // If a is odd, // multiply x with result if (b & 1) res = (res * a) % mod; // b must be even now b = b >> 1; // b = b/2 a = (a * a) % mod; } return res;}// DFS traversal of the nodesvoid dfs(int i, int& size, bool* visited) { // Mark the current // node as visited visited[i] = true; // Increment the size of the // current component size++; // Recur for all the vertices // adjacent to this node for (auto nbr : G[i]) { if (!visited[nbr]) { dfs(nbr, size, visited); } }}// Function to calculate the// final answervoid totalSequences(int& ans, int n, int k){ // Mark all the vertices as // not visited initially bool visited[n + 1]; memset(visited, false, sizeof(visited)); // Subtract (size^k) from the answer // for different components for (int i = 1; i <= n; i++) { if (!visited[i]) { int size = 0; dfs(i, size, visited); ans -= power(size, k); ans += mod; ans = ans % mod; } }}// Function to add edges to the graphvoid addEdge(int x, int y, int color){ // If the colour is green, // include it in the graph if (color == 0) { G[x].push_back(y); G[y].push_back(x); }}int32_t main(){ // Number of node in the tree int n = 3; // Size of sequence int k = 3; // Initiaize the result as n^k int ans = power(n, k); /* 2 / \ 1 3 Let us create binary tree as shown in above example */ addEdge(1, 2, 1); addEdge(2, 3, 1); totalSequences(ans, n, k); cout << ans << endl;} |
Java
// Java implementation of the// above approachimport java.util.*;class GFG{static int mod = (int)(1e9 + 7);static int N = (int)(1e5 + 1);static int size;static int ans;// Vector to store the graph@SuppressWarnings("unchecked")static Vector<Integer> []G = new Vector[N];// Iterative Function to calculate// (a<sup>b</sup>) % mod in O(log b)static int power(int a, int b){ // Initialize result int res = 1; // Update x if it is more than // or equal to p a = a % mod; if (a == 0) // In case x is divisible by p; return 0; while (b > 0) { // If a is odd, // multiply x with result if (b % 2 == 1) res = (res * a) % mod; // b must be even now b = b >> 1; // b = b/2 a = (a * a) % mod; } return res;}// DFS traversal of the nodesstatic void dfs(int i, boolean []visited){ // Mark the current // node as visited visited[i] = true; // Increment the size of the // current component size++; // Recur for all the vertices // adjacent to this node for(int nbr : G[i]) { if (!visited[nbr]) { dfs(nbr, visited); } }}// Function to calculate the// final answerstatic void totalSequences(int n, int k){ // Mark all the vertices as // not visited initially boolean []visited = new boolean[n + 1]; // Subtract (size^k) from the answer // for different components for(int i = 1; i <= n; i++) { if (!visited[i]) { size = 0; dfs(i, visited); ans -= power(size, k); ans += mod; ans = ans % mod; } }}// Function to add edges to the graphstatic void addEdge(int x, int y, int color){ // If the colour is green, // include it in the graph if (color == 0) { G[x].add(y); G[y].add(x); }}// Driver codepublic static void main(String[] args){ for(int i = 0; i < G.length; i++) G[i] = new Vector<Integer>(); // Number of node in the tree int n = 3; // Size of sequence int k = 3; // Initiaize the result as n^k ans = power(n, k); /* 2 / \ 1 3 Let us create binary tree as shown in above example */ addEdge(1, 2, 1); addEdge(2, 3, 1); totalSequences(n, k); System.out.print(ans + "\n");}}// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approachmod = 1e9 + 7N = 1e5 + 1# List to store the graphG = [0] * int(N)# Iterative Function to calculate# (a<sup>b</sup>) % mod in O(log b)def power(a, b): # Initialize result res = 1 # Update x if it is more than # or equal to p a = a % mod if a == 0: # In case x is divisible by p; return 0 while b > 0: # If a is odd, # multiply x with result if b & 1: res = (res * a) % mod # b must be even now b = b >> 1 # b = b/2 a = (a * a) % mod return res# DFS traversal of the nodesdef dfs(i, size, visited): # Mark the current # node as visited visited[i] = True # Increment the size of the # current component size[0] += 1 # Recur for all the vertices # adjacent to this node for nbr in range(G[i]): if not visited[nbr]: dfs(nbr, size, visited)# Function to calculate the# final answerdef totalSequences(ans, n, k): # Mark all the vertices as # not visited initially visited = [False] * (n + 1) # Subtract (size^k) from the answer # for different components for i in range(1, n + 1): if not visited[i]: size = [0] dfs(i, size, visited) ans[0] -= power(size[0], k) ans[0] += mod ans[0] = ans[0] % mod# Function to add edges to the graphdef addEdge(x, y, color): # If the colour is green, # include it in the graph if color == 0: G[x].append(y) G[y].append(x)# Driver codeif __name__ == '__main__': # Number of node in the tree n = 3 # Size of sequence k = 3 # Initiaize the result as n^k ans = [power(n, k)] """ 2 / \ 1 3 Let us create binary tree as shown in above example """ addEdge(1, 2, 1) addEdge(2, 3, 1) totalSequences(ans, n, k) print(int(ans[0]))# This code is contributed by Shivam Singh |
C#
// C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG{static int mod = (int)(1e9 + 7);static int N = (int)(1e5 + 1);static int size;static int ans;// List to store the graphstatic List<int> []G = new List<int>[N];// Iterative Function to// calculate (a<sup>b</sup>)// % mod in O(log b)static int power(int a, int b){ // Initialize result int res = 1; // Update x if it is // more than or equal // to p a = a % mod; if (a == 0) // In case x is // divisible by p; return 0; while (b > 0) { // If a is odd, // multiply x // with result if (b % 2 == 1) res = (res * a) % mod; // b must be even now // b = b/2 b = b >> 1; a = (a * a) % mod; } return res;}// DFS traversal of the nodesstatic void dfs(int i, bool []visited){ // Mark the current // node as visited visited[i] = true; // Increment the size of the // current component size++; // Recur for all the vertices // adjacent to this node foreach(int nbr in G[i]) { if (!visited[nbr]) { dfs(nbr, visited); } }}// Function to calculate the// readonly answerstatic void totalSequences(int n, int k){ // Mark all the vertices as // not visited initially bool []visited = new bool[n + 1]; // Subtract (size^k) from the // answer for different components for(int i = 1; i <= n; i++) { if (!visited[i]) { size = 0; dfs(i, visited); ans -= power(size, k); ans += mod; ans = ans % mod; } }}// Function to add edges// to the graphstatic void addEdge(int x, int y, int color){ // If the colour is green, // include it in the graph if (color == 0) { G[x].Add(y); G[y].Add(x); }}// Driver codepublic static void Main(String[] args){ for(int i = 0; i < G.Length; i++) G[i] = new List<int>(); // Number of node // in the tree int n = 3; // Size of sequence int k = 3; // Initiaize the // result as n^k ans = power(n, k); /* 2 / \ 1 3 Let us create binary tree as shown in above example */ addEdge(1, 2, 1); addEdge(2, 3, 1); totalSequences(n, k); Console.Write(ans + "\n");}}// This code is contributed by Rajput-Ji |
Javascript
<script> // Javascript implementation of the above approach let mod = (1e9 + 7); let N = (1e5 + 1); let size; let ans; // List to store the graph let G = new Array(N); // Iterative Function to // calculate (a<sup>b</sup>) // % mod in O(log b) function power(a, b) { // Initialize result let res = 1; // Update x if it is // more than or equal // to p a = a % mod; if (a == 0) // In case x is // divisible by p; return 0; while (b > 0) { // If a is odd, // multiply x // with result if (b % 2 == 1) res = (res * a) % mod; // b must be even now // b = b/2 b = b >> 1; a = (a * a) % mod; } return res; } // DFS traversal of the nodes function dfs(i, visited) { // Mark the current // node as visited visited[i] = true; // Increment the size of the // current component size++; // Recur for all the vertices // adjacent to this node for(let nbr = 0; nbr < G[i].length; nbr++) { if (!visited[G[i][nbr]]) { dfs(G[i][nbr], visited); } } } // Function to calculate the // readonly answer function totalSequences(n, k) { // Mark all the vertices as // not visited initially let visited = new Array(n + 1); visited.fill(false); // Subtract (size^k) from the // answer for different components for(let i = 1; i <= n; i++) { if (!visited[i]) { size = 0; dfs(i, visited); ans -= power(size, k); ans += mod; ans = ans % mod; } } } // Function to add edges // to the graph function addEdge(x, y, color) { // If the colour is green, // include it in the graph if (color == 0) { G[x].push(y); G[y].push(x); } } for(let i = 0; i < G.length; i++) G[i] = []; // Number of node // in the tree let n = 3; // Size of sequence let k = 3; // Initiaize the // result as n^k ans = power(n, k); /* 2 / \ 1 3 Let us create binary tree as shown in above example */ addEdge(1, 2, 1); addEdge(2, 3, 1); totalSequences(n, k); document.write(ans + "</br>");</script> |
24
Time Complexity: O(N), Since DFS traversal requires O(Vertices + Edges) == O(N + (N-1)) == O(N) ) complexity.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes


