snippets 0.1.0
Loading...
Searching...
No Matches
disjoint_set.hpp
Go to the documentation of this file.
1#ifndef DISJOINT_SET_H
2#define DISJOINT_SET_H
3
4namespace hsc_snippets
5{
6#include <vector>
7
9 {
10 private:
11 std::vector<int> parent;
12 std::vector<int> rank;
13 int count; // Number of distinct sets
14
15 public:
20 explicit DisjointSet(int size) : parent(size), rank(size, 0), count(size)
21 {
22 for (int i = 0; i < size; ++i)
23 {
24 parent[i] = i;
25 }
26 }
27
33 int find(int p)
34 {
35 if (parent[p] != p)
36 {
37 parent[p] = find(parent[p]); // Path compression
38 }
39 return parent[p];
40 }
41
47 void unionSets(int p, int q)
48 {
49 int rootP = find(p);
50 int rootQ = find(q);
51
52 if (rootP == rootQ)
53 return; // 'p' and 'q' are already in the same set.
54
55 // Merge smaller set into the larger one.
56 if (rank[rootP] < rank[rootQ])
57 {
58 parent[rootP] = rootQ;
59 }
60 else if (rank[rootP] > rank[rootQ])
61 {
62 parent[rootQ] = rootP;
63 }
64 else
65 {
66 parent[rootQ] = rootP;
67 rank[rootP] += 1; // Increase the rank if both have the same rank.
68 }
69
70 count--; // Decrease the number of sets
71 }
72
77 int getCount() const
78 {
79 return count;
80 }
81 };
82
83}
84
85#endif // DISJOINT_SET_H
Definition disjoint_set.hpp:9
DisjointSet(int size)
Construct a new Disjoint Set object.
Definition disjoint_set.hpp:20
int find(int p)
Find the set containing element 'p'.
Definition disjoint_set.hpp:33
int getCount() const
Get the number of distinct sets.
Definition disjoint_set.hpp:77
void unionSets(int p, int q)
Union the sets containing elements 'p' and 'q'.
Definition disjoint_set.hpp:47
Definition big_integer.hpp:14