PhonePe || Connected Components in a Graph after removing nodes one by one.

459
Oct 10, 2022
Nov 21, 2022

The questions basically boils down to this :
Given n cities numbered 1 to n and m edges, count the number of components after cities are removed one after other (when a city is removed all its edges are also removed).
i.e City1, City 2 and so on.(ascending order)

Thought Process

  1. As the cities are removed in ascending order we store the given edges in a adjacency matrix where we store the edge from u to v if, u < v
    else v to u if v<u
  2. Now we use Union find to count the number of components,
    • we add edges from the last node
    • for every merge operation we decrement the count of components and store the value in an array
  3. Now we reverse our ans array and print it
    • the last output will always be 0 as no cities remain.

Input Format
N M
A1 B1
A2 B2
.
.
AM BM
(Ai,Bi represents City number).
Constraints
1<=N<=200000
0<=M<=min(200000,(N(N-1))/2)
1<=Ai All values in input are integers.

Output Format
Print N lines.
The i-th line should contain the number of connected components when a city is exploded.

Sample Input 0

6 7
1 2
1 4
1 5
2 4
2 3
3 5
3 6

Sample Output 0

1
2
3
2
1
0

Time Complexity = O(E)
E = Number of edges, V = Number of vertices.

MY SOLUTION

#include<bits/stdc++.h>
using namespace std;

const int N=2e5+7;
vector<int> adj[N]; //adj matrix to store edges

int cc; // global variable to count connected components

int find(int i,vector<int>&parent){
    if(i==parent[i])return i;
    return parent[i]=find(parent[i],parent);
}

void merge(int u,int v,vector<int>&parent,vector<int>&rank){
    int s1=find(u,parent),s2=find(v,parent);
    if(s1!=s2){
        if(rank[s1]>rank[s2]){
            rank[s1]+=rank[s2];
            parent[s2]=s1;
        }
        else{
            rank[s2]+=rank[s1];
            parent[s1]=s2;
        }
        cc--;
    }
}

int main(){
    int n,m;
    cin>>n>>m;
    vector<int>parent(n+2,0),rank(n+2,1);
    iota(parent.begin(),parent.end(),0); //initialise parent[i]=i
    for(int i=0;i<m;i++){
        int u,v;
        cin>>u>>v;
        if(u<v){ //helps when we have to remove/add edges our code
            adj[u].push_back(v);
        }
        else{
            adj[v].push_back(u);
        }
    }

    
    cc=0; //count of connected componets are intially 0 as no nodes 
    vector<int>ans;
    ans.push_back(0); // when no cities are  there so 0 connected components
    for(int i=n;i>=1;i--){
        cc++;
        for(auto nbr:adj[i]){
            merge(i,nbr,parent,rank);
        }
        ans.push_back(cc);
    }
    reverse(ans.begin(),ans.end());
    for(int i=1;i<ans.size();i++)cout<<ans[i]<<endl;
}

Please let me know if it can be improved further.

Comments (0)