Queries to count connected components after removal of a vertex from a Tree - GeeksforGeeks

07 Oct, 2021
Given a Tree consisting of N nodes valued in the range [0, N) and an array Queries[] of Q integers consisting of values in the range [0, N). The task for each query is to remove the vertex valued Q[i] and count the connected components in the resulting graph.
Examples:
Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {0, 1, 6}  
Output:3 3 1Explanation:Query 1: Removal of the node valued 0 leads to removal of the edges (0, 1), (0, 2) and (0, 3). Therefore, the remaining graph has 3 connected components: [1, 4, 5], [2], [3, 6]Query 2:Removal of the node valued 1 leads to removal of the edges (1, 4), (1, 5) and (1, 0). Therefore, remaining graph has 3 connected components: [4], [5], [2, 0, 3, 6]Query 3:Removal of the node valued 6 leads to removal of the edges (3, 6). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 5].
Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {5, 3, 2}  
Output:1 2 1Explanation:Query 1: Removal of the node valued 5 leads to removal of the edge (1, 5). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 6]Query 2:Removal of the node valued 3 leads to removal of the edges (0, 3), (3, 6). Therefore, the remaining graph has 2 connected components: [0, 1, 2, 4, 5], [6]Query 3: Removal of the node valued 2 leads to removal of the edge (0, 2). Therefore, the remaining graph has 1 connected component: [0, 1, 3, 4, 5, 6]
Approach: The idea is to observe that in a Tree, whenever a node is deleted, the nodes which were connected together to that node get separated. So, the count of connected components becomes equal to the degree of the deleted node.Therefore, the approach is to precompute and store the degree of each node in an array. For every query, the count of the connected components is simply the degree of the corresponding node in the query.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define MAX 100005 // Stores degree of the nodesint degree[MAX]; // Function that finds the degree of// each node in the given graphvoid DegreeOfNodes(int Edges[][2],                   int N){    // Precompute degrees of each node    for (int i = 0; i < N - 1; i++) {        degree[Edges[i][0]]++;        degree[Edges[i][1]]++;    }} // Function to print the number of// connected componentsvoid findConnectedComponents(int x){    // Print the degree of node x    cout << degree[x] << ' ';} // Function that counts the connected// components after removing a vertex// for each queryvoid countCC(int N, int Q, int Queries[],             int Edges[][2]){     // Count degree of each node    DegreeOfNodes(Edges, N);     // Iterate over each query    for (int i = 0; i < Q; i++) {         // Find connected components        // after removing given vertex        findConnectedComponents(Queries[i]);    }} // Driver Codeint main(){    // Given N nodes and Q queries    int N = 7, Q = 3;     // Given array of queries    int Queries[] = { 0, 1, 6 };     // Given Edges    int Edges[][2] = { { 0, 1 }, { 0, 2 },                       { 0, 3 }, { 1, 4 },                       { 1, 5 }, { 3, 6 } };     // Function Call    countCC(N, Q, Queries, Edges);     return 0;}
// Java program for// the above approachimport java.util.*;class GFG{   static final int MAX  = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [][]Edges,                          int N){  // Precompute degrees of each node  for (int i = 0; i < N - 1; i++)  {    degree[Edges[i][0]]++;    degree[Edges[i][1]]++;  }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){  // Print the degree of node x  System.out.print(degree[x] + " ");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q,                    int Queries[],                    int [][]Edges){  // Count degree of each node  DegreeOfNodes(Edges, N);   // Iterate over each query  for (int i = 0; i < Q; i++)  {    // Find connected components    // after removing given vertex    findConnectedComponents(Queries[i]);  }} // Driver Codepublic static void main(String[] args){  // Given N nodes and Q queries  int N = 7, Q = 3;   // Given array of queries  int Queries[] = {0, 1, 6};   // Given Edges  int [][]Edges = {{0, 1}, {0, 2},                   {0, 3}, {1, 4},                   {1, 5}, {3, 6}};   // Function Call  countCC(N, Q, Queries, Edges);}} // This code is contributed by Rajput-Ji
# Python3 program for the above approachMAX = 100005 # Stores degree of the nodesdegree = [0] * MAX # Function that finds the degree of# each node in the given graphdef DegreeOfNodes(Edges, N):         # Precompute degrees of each node    for i in range(N - 1):        degree[Edges[i][0]] += 1        degree[Edges[i][1]] += 1 # Function to print the number of# connected componentsdef findConnectedComponents(x):         # Print the degree of node x    print(degree[x], end = " ") # Function that counts the connected# components after removing a vertex# for each querydef countCC(N, Q, Queries, Edges):     # Count degree of each node    DegreeOfNodes(Edges, N)     # Iterate over each query    for i in range(Q):         # Find connected components        # after removing given vertex        findConnectedComponents(Queries[i]) # Driver Codeif __name__ == '__main__':         # Given N nodes and Q queries    N = 7    Q = 3     # Given array of queries    Queries = [ 0, 1, 6 ]     # Given Edges    Edges = [ [ 0, 1 ], [ 0, 2 ],              [ 0, 3 ], [ 1, 4 ],              [ 1, 5 ], [ 3, 6 ] ]     # Function call    countCC(N, Q, Queries, Edges) # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;class GFG{   static readonly int MAX  = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [,]Edges,                          int N){  // Precompute degrees of each node  for (int i = 0; i < N - 1; i++)  {    degree[Edges[i, 0]]++;    degree[Edges[i, 1]]++;  }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){  // Print the degree of node x  Console.Write(degree[x] + " ");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q,                    int []Queries,                    int [,]Edges){  // Count degree of each node  DegreeOfNodes(Edges, N);   // Iterate over each query  for (int i = 0; i < Q; i++)  {    // Find connected components    // after removing given vertex    findConnectedComponents(Queries[i]);  }} // Driver Codepublic static void Main(String[] args){  // Given N nodes and Q queries  int N = 7, Q = 3;   // Given array of queries  int []Queries = {0, 1, 6};   // Given Edges  int [,]Edges = {{0, 1}, {0, 2},                  {0, 3}, {1, 4},                  {1, 5}, {3, 6}};   // Function Call  countCC(N, Q, Queries, Edges);}} // This code is contributed by shikhasingrajput
<script> // Javascript program for the above approachvar MAX = 100005 // Stores degree of the nodesvar degree = Array(MAX).fill(0) // Function that finds the degree of// each node in the given graphfunction DegreeOfNodes(Edges, N){    // Precompute degrees of each node    for (var i = 0; i < N - 1; i++) {        degree[Edges[i][0]]++;        degree[Edges[i][1]]++;    }} // Function to print the number of// connected componentsfunction findConnectedComponents(x){    // Print the degree of node x    document.write( degree[x] + ' ');} // Function that counts the connected// components after removing a vertex// for each queryfunction countCC(N, Q, Queries, Edges){     // Count degree of each node    DegreeOfNodes(Edges, N);     // Iterate over each query    for (var i = 0; i < Q; i++) {         // Find connected components        // after removing given vertex        findConnectedComponents(Queries[i]);    }} // Driver Code// Given N nodes and Q queriesvar N = 7, Q = 3;// Given array of queriesvar Queries = [ 0, 1, 6 ];// Given Edgesvar Edges = [ [ 0, 1 ], [ 0, 2 ],                   [ 0, 3 ], [ 1, 4 ],                   [ 1, 5 ], [ 3, 6 ] ];// Function CallcountCC(N, Q, Queries, Edges);  </script>
3 3 1
 
Time Complexity: O(E + Q), where E is the number of edges(E = N – 1) and Q is the number of queries.Auxiliary Space: O(V), where V is number the of vertices.
mohit kumar 29
Rajput-Ji
shikhasingrajput
famously
surinderdawra388
anikakapoor
connected-components
graph-connectivity
Graph
Tree
Graph
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)