-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.cpp
More file actions
69 lines (50 loc) · 1.43 KB
/
Copy pathUnionFind.cpp
File metadata and controls
69 lines (50 loc) · 1.43 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
66
67
68
69
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class UnionFind{
private:
vector<int> parent;
size_t comps;
public:
UnionFind(const size_t& n) : parent(vector<int>(n, -1)), comps(n) {}
bool join(size_t x, size_t y){
size_t bx = find(x);
size_t by = find(y);
if(bx == by) return false; // cycle detected
if(parent[bx] < parent[by]){ // x has more elements in its component
parent[bx] += parent[by];
parent[by] = bx;
}
else{ // y has more elements in his component
parent[by] += parent[bx];
parent[bx] = by;
}
--comps;
return true;
}
size_t find(size_t x){
size_t boss = x;
while(parent[boss] > -1) boss = parent[boss];
while(x != boss){
if(parent[x]!=boss) parent[parent[x]] = boss;
x = parent[x];
}
return boss;
}
size_t connected_comps() const {
return comps;
}
void display() const {
// display vector with brackets
cout << "[";
for(size_t i=0; i<parent.size(); ++i){
cout << parent[i];
if(i != parent.size()-1) cout << ", ";
}
cout << "]" << endl;
}
vector<int> content() const {
return parent;
}
};