forked from dharmanshu1921/Daa-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisjointSet.cpp
77 lines (66 loc) · 1.69 KB
/
DisjointSet.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
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <vector>
using namespace std;
class DisjointSet {
vector<int> parent;
vector<int> rank;
public:
DisjointSet(int n) {
parent.resize(n+1);
rank.resize(n+1);
for (int i=0; i<=n; i++) {
makeSet(i);
}
}
void makeSet(int a) {
parent[a] = a;
rank[a] = 1;
}
void unionSet(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return;
if (rank[ra] > rank[rb]) {
parent[rb] = ra;
} else if (rank[ra] < rank[rb]) {
parent[ra] = rb;
} else {
parent[rb] = ra;
rank[ra]++;
}
}
int find(int a) {
if (parent[a] != a) {
parent[a] = find(parent[a]);
}
return parent[a];
}
bool connected(int a, int b) {
return (find(a) == find(b));
}
};
int main() {
int n;
cout << "Enter no. of vertices: ";
cin >> n;
DisjointSet* set = new DisjointSet(n);
// cout << "Enter no. of connections: ";
// cin >> n;
while (n--) {
int a, b;
cout << "Enter vertice1 and vertice2: ";
cin >> a >> b;
bool conn = set->connected(a, b);
if (!conn) {
set->unionSet(a, b);
}
}
for (int i=0; i<3; i++) {
int a, b;
cout << "Enter vertices to check connection: ";
cin >> a >> b;
bool conn = set->connected(a, b);
if (conn) cout << "Connected" << endl;
else cout << "Disconnected" << endl;
}
}