Skip to content

Commit 5006703

Browse files
Merge pull request matthewsamuel95#650 from anishbadhri/patch-3
Created ConnectedComponent.cpp
2 parents 86ac54b + a64af27 commit 5006703

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
5+
class DSU{
6+
std::vector<int> parent;
7+
int connected_component;
8+
public:
9+
DSU(int n){ parent = vector<int>(n,-1); connected_component = n; }
10+
int findParent(int n){
11+
if(parent[n] == -1)
12+
return n;
13+
parent[n] = findParent(parent[n]); //Path Compression
14+
return parent[n];
15+
}
16+
void unionSet(int a,int b){
17+
int x = findParent(a);
18+
int y = findParent(b);
19+
if(x!=y){
20+
parent[x] = y;
21+
connected_component--;
22+
}
23+
}
24+
int getConnectedComponent(){return connected_component;}
25+
};
26+
27+
/*
28+
Input Format:
29+
First line consists of 2 integers, 'n' and 'e' denoting number of nodes and edges respectively.
30+
The next 'e' lines each contain 2 integers x and y, where 1<=x,y<=n, denoting an edge between node x and node y
31+
*/
32+
int main(){
33+
int n,e;
34+
cin>>n>>e;
35+
DSU d(n);
36+
int x,y;
37+
while(e--){
38+
cin>>x>>y;
39+
d.unionSet(x,y);
40+
}
41+
cout<<"\nNumber of connected components : "<<d.getConnectedComponent()<<endl;
42+
}

0 commit comments

Comments
 (0)