-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisjoiintset.cpp
More file actions
59 lines (54 loc) · 964 Bytes
/
disjoiintset.cpp
File metadata and controls
59 lines (54 loc) · 964 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
using namespace std;
class DisjoinSet{
vector<int> parent, rank;
public:
DisjoinSet(int n){
parent.resize(n,0);
rank.resize(n,0);
for(int i=0;i<n;i++){
parent[i]=i;
}
}
int findUParent(int u){
if(u == parent[u]){
return u;
}
else{
return parent[u] = findUParent(parent[u]);
}
}
void UnionByRank(int u, int v){
int u_p_v = findUParent(v);
int u_p_u = findUParent(u);
if(u_p_u == u_p_v){
return ;
}
if(rank[u_p_u] > rank[u_p_v]){
parent[u_p_v] = u_p_u;
}
else if(rank[u_p_v] > rank[u_p_u]){
parent[u_p_u] = u_p_v;
}
else{
parent[u_p_u] = u_p_v;
rank[u_p_v]++;
}
}
};
int main(){
int n;
cin>>n;
DisjoinSet disjointSet(7);
for(int i=0;i<n;i++){
int sou, des;
cin>>sou>>des;
disjointSet.UnionByRank(sou,des);
}
if(disjointSet.findUParent(1) == disjointSet.findUParent(4)){
cout<<"Both belongs to same component";
}
else{
cout<<"Different components";
}
}