|
6 | 6 | #include <vector> |
7 | 7 |
|
8 | 8 | namespace weilycoder { |
| 9 | +/** |
| 10 | + * @brief Union-Find (Disjoint Set Union) Data Structure |
| 11 | + * @tparam ptr_t Type for representing indices (default: size_t) |
| 12 | + */ |
9 | 13 | template <typename ptr_t = size_t> struct UnionFind { |
10 | | - std::vector<ptr_t> parent, size; |
| 14 | +private: |
| 15 | + std::vector<ptr_t> parent, setSize; |
11 | 16 |
|
12 | | - UnionFind(ptr_t n) : parent(n), size(n, 1) { |
| 17 | +public: |
| 18 | + /** |
| 19 | + * @brief Constructs a UnionFind with n elements, each in its own set |
| 20 | + * @param n Number of elements |
| 21 | + */ |
| 22 | + UnionFind(ptr_t n) : parent(n), setSize(n, 1) { |
13 | 23 | std::iota(parent.begin(), parent.end(), 0); |
14 | 24 | } |
15 | 25 |
|
| 26 | + /** |
| 27 | + * @brief Returns the number of elements |
| 28 | + * @return Number of elements |
| 29 | + */ |
| 30 | + size_t size() const { return parent.size(); } |
| 31 | + |
| 32 | + /** |
| 33 | + * @brief Returns the size of the set containing x |
| 34 | + * @param x Element to query |
| 35 | + * @return Size of the set containing x |
| 36 | + */ |
| 37 | + size_t get_size(ptr_t x) { return setSize[getf(x)]; } |
| 38 | + |
| 39 | + /** |
| 40 | + * @brief Finds the representative of the set containing x |
| 41 | + * @param x Element to find |
| 42 | + * @return Representative of the set containing x |
| 43 | + */ |
16 | 44 | ptr_t getf(ptr_t x) { |
17 | 45 | while (x != parent[x]) |
18 | 46 | x = parent[x] = parent[parent[x]]; |
19 | 47 | return x; |
20 | 48 | } |
21 | 49 |
|
| 50 | + /** |
| 51 | + * @brief Unites the sets containing x and y |
| 52 | + * @param x First element |
| 53 | + * @param y Second element |
| 54 | + * @return True if the sets were separate and have been united, false if they |
| 55 | + * were already in the same set |
| 56 | + */ |
22 | 57 | bool unite(ptr_t x, ptr_t y) { |
23 | 58 | x = getf(x), y = getf(y); |
24 | 59 | if (x == y) |
25 | 60 | return false; |
26 | | - if (size[x] < size[y]) |
| 61 | + if (setSize[x] < setSize[y]) |
27 | 62 | std::swap(x, y); |
28 | | - parent[y] = x, size[x] += size[y]; |
| 63 | + parent[y] = x, setSize[x] += setSize[y]; |
29 | 64 | return true; |
30 | 65 | } |
31 | 66 | }; |
|
0 commit comments