forked from hackelite01/hacktoberfest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijointset.cpp
67 lines (57 loc) · 1.27 KB
/
dijointset.cpp
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
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
int rankOfElement[11];
int parent[11];
int n = 10;
void makeSet(){
for(int i = 1; i <= n; i++) {
rankOfElement[i] = 0;
parent[i] = i;
}
}
int findPar(int node) {
if(parent[node] == node) {
return node;
}
return parent[node] = findPar(parent[node]);
}
void unionOfSet(int u, int v) {
u = findPar(u);
v = findPar(v);
if(rankOfElement[u] < rankOfElement[v]) {
parent[u] = v;
}
else if(rankOfElement[v] < rankOfElement[u]) {
parent[v] = u;
}
else {
parent[u] = v;
rankOfElement[v]++;
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
makeSet();
int m;
cin >> m;
while(m--) {
int u, v;
cin >> u >> v;
unionOfSet(u, v);
}
if(findPar(1) != findPar(4)) {
cout << "Different component" << "\n";
}
else{
cout << "1 and 4 are in same component." << "\n";
}
if(findPar(1) == findPar(5)){
cout << "Same component." << "\n";
}
else{
cout << "1 and 5 are in different component." << "\n";
}
}