-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnionFind.hpp
82 lines (69 loc) · 1.98 KB
/
UnionFind.hpp
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
78
79
80
81
82
#ifndef CAV_INCLUDE_UNIONFIND_HPP
#define CAV_INCLUDE_UNIONFIND_HPP
#include <cassert>
#include <cstddef>
#include <vector>
namespace cav {
template <typename Int = size_t>
class UnionFind {
public:
struct Node {
Int size, parent;
};
explicit UnionFind(Int size)
: components_num(size) {
nodes.resize(size);
for (Int i = 0; i < size; ++i)
nodes[i] = {1, i};
}
inline Int make_set() {
Int old_size = nodes.size();
nodes.emplace_back(1, old_size);
++components_num;
return old_size;
}
[[nodiscard]] Int find(Int n) {
assert(static_cast<size_t>(n) < nodes.size());
Int& p = nodes[n].parent;
if (n != p)
p = find(p);
return p;
}
inline bool link_nodes(Int r1, Int r2) {
assert(static_cast<size_t>(r1) < nodes.size());
assert(static_cast<size_t>(r2) < nodes.size());
if (r1 != r2) {
if (nodes[r1].size >= nodes[r2].size) {
nodes[r2].parent = r1;
nodes[r1].size += nodes[r2].size;
} else {
nodes[r1].parent = r2;
nodes[r2].size += nodes[r1].size;
}
assert(components_num > 1);
--components_num;
return false;
}
return true;
}
inline bool union_nodes(Int n1, Int n2) {
assert(static_cast<size_t>(n1) < nodes.size());
assert(static_cast<size_t>(n2) < nodes.size());
return link_nodes(find(n1), find(n2));
}
[[nodiscard]] Int get_comp_size(Int n) {
assert(static_cast<size_t>(n) < nodes.size());
return nodes[find(n)].size;
}
[[nodiscard]] size_t get_components_num() const {
return components_num;
}
[[nodiscard]] size_t size() const {
return nodes.size();
}
private:
std::vector<Node> nodes;
size_t components_num = 0;
};
} // namespace cav
#endif /* CAV_INCLUDE_UNIONFIND_HPP */