-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDisjointSets.cpp
More file actions
35 lines (30 loc) · 1003 Bytes
/
DisjointSets.cpp
File metadata and controls
35 lines (30 loc) · 1003 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
class DisjointSets {
int n;
vector < int > parent, rank;
public:
DisjointSets(int n) {
this->n = n;
rank.resize(n), parent.resize(n);
for (int i = 0; i < n; i++) rank[i] = 0, parent[i] = i;
}
int findParent(int u){
if (u == parent[u]) return u;
return parent[u] = findParent(parent[u]);
}
void merge(int x, int y){
int rootX = findParent(x), rootY = findParent(y);
if (rootX != rootY) { // Make tree with smaller height a subtree of the other tree
if (rank[rootX] > rank[rootY]) parent[rootY] = rootX;
else if (rank[rootX] < rank[rootY]) parent[rootX] = rootY;
else parent[rootY] = rootX, rank[rootX] += 1;
}
}
bool connected(int x, int y) {
return findParent(x) == findParent(y);
}
int numComponents(){
int conn = 0;
for(int i = 0; i < n; i++) if(parent[i] == i) conn++;
return conn;
}
};