-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathUnionFind.cpp
More file actions
66 lines (55 loc) · 1.47 KB
/
UnionFind.cpp
File metadata and controls
66 lines (55 loc) · 1.47 KB
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
// Implementation of Union Find / Disjoint Set Union (DSU) in C++
/*
* DSU object will be instantiated and called as such:
* UnionFind uf(n);
* uf.unite(x, y);
* int parent = uf.findRootOf(x);
* bool connected = uf.isConnected(x, y);
*/
#include <vector>
using namespace std;
class UnionFind {
private:
vector<int> root;
vector<int> rank;
int sets;
public:
// Constructor to create n sets
UnionFind(int n) {
root.resize(n);
rank.resize(n, 1);
sets = n;
for (int i = 0; i < n; ++i) {
root[i] = i;
}
}
// Find the root of x (with path compression)
int findRootOf(int x) {
if (root[x] != x) {
root[x] = findRootOf(root[x]); // Path compression
}
return root[x];
}
// Unite the sets containing x and y
void unite(int x, int y) {
int rootX = findRootOf(x);
int rootY = findRootOf(y);
// If they are already in the same set, return
if (rootX == rootY) {
return;
}
// Union by rank
if (rank[rootY] > rank[rootX]) {
root[rootX] = rootY;
rank[rootY] += rank[rootX];
} else {
root[rootY] = rootX;
rank[rootX] += rank[rootY];
}
sets--; // Decrease number of sets
}
// Check if x and y are connected (belong to the same set)
bool isConnected(int x, int y) {
return findRootOf(x) == findRootOf(y);
}
};