Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 26 May, 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 1
Explanation:
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 1
Explanation:
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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
 
// Stores degree of the nodes
int degree[MAX];
 
// Function that finds the degree of
// each node in the given graph
void 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 components
void findConnectedComponents(int x)
{
    // Print the degree of node x
    cout << degree[x] << ' ';
}
 
// Function that counts the connected
// components after removing a vertex
// for each query
void countCC(int N, int Q, int Queries[],
             int Edges[][2])
{
 
    // Count degree of each node
    DegreeOfNodes(Edges, N);
 
    // Interate over each query
    for (int i = 0; i < Q; i++) {
 
        // Find connected components
        // after removing given vertex
        findConnectedComponents(Queries[i]);
    }
}
 
// Driver Code
int 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




// Java program for
// the above approach
import java.util.*;
class GFG{
   
static final int MAX  = 100005;
 
// Stores degree of the nodes
static int []degree = new int[MAX];
 
// Function that finds the degree of
// each node in the given graph
static 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 components
static 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 query
static void countCC(int N, int Q,
                    int Queries[],
                    int [][]Edges)
{
  // Count degree of each node
  DegreeOfNodes(Edges, N);
 
  // Interate over each query
  for (int i = 0; i < Q; i++)
  {
    // Find connected components
    // after removing given vertex
    findConnectedComponents(Queries[i]);
  }
}
 
// Driver Code
public 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




# Python3 program for the above approach
MAX = 100005
 
# Stores degree of the nodes
degree = [0] * MAX
 
# Function that finds the degree of
# each node in the given graph
def 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 prthe number of
# connected components
def findConnectedComponents(x):
     
    # Print the degree of node x
    print(degree[x], end = " ")
 
# Function that counts the connected
# components after removing a vertex
# for each query
def countCC(N, Q, Queries, Edges):
 
    # Count degree of each node
    DegreeOfNodes(Edges, N)
 
    # Interate over each query
    for i in range(Q):
 
        # Find connected components
        # after removing given vertex
        findConnectedComponents(Queries[i])
 
# Driver Code
if __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#




// C# program for
// the above approach
using System;
class GFG{
   
static readonly int MAX  = 100005;
 
// Stores degree of the nodes
static int []degree = new int[MAX];
 
// Function that finds the degree of
// each node in the given graph
static 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 components
static 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 query
static void countCC(int N, int Q,
                    int []Queries,
                    int [,]Edges)
{
  // Count degree of each node
  DegreeOfNodes(Edges, N);
 
  // Interate over each query
  for (int i = 0; i < Q; i++)
  {
    // Find connected components
    // after removing given vertex
    findConnectedComponents(Queries[i]);
  }
}
 
// Driver Code
public 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

Javascript




<script>
 
// Javascript program for the above approach
var MAX = 100005
 
// Stores degree of the nodes
var degree = Array(MAX).fill(0)
 
// Function that finds the degree of
// each node in the given graph
function 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 components
function findConnectedComponents(x)
{
    // Print the degree of node x
    document.write( degree[x] + ' ');
}
 
// Function that counts the connected
// components after removing a vertex
// for each query
function countCC(N, Q, Queries, Edges)
{
 
    // Count degree of each node
    DegreeOfNodes(Edges, N);
 
    // Interate 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 queries
var N = 7, Q = 3;
// Given array of queries
var Queries = [ 0, 1, 6 ];
// Given Edges
var Edges = [ [ 0, 1 ], [ 0, 2 ],
                   [ 0, 3 ], [ 1, 4 ],
                   [ 1, 5 ], [ 3, 6 ] ];
// Function Call
countCC(N, Q, Queries, Edges);
 
 
</script>
Output: 
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.

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 experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :