GraphLibrary  0.0.1
A simple library that implements various graph algorithms.
 All Classes Namespaces Files Functions Variables Typedefs Macros
DisjointSets.hpp
Go to the documentation of this file.
1 #ifndef GL_DISJOINT_SETS_HPP
2 #define GL_DISJOINT_SETS_HPP
3 
4 #include "../gl_base.hpp"
5 
6 #include <vector>
7 
8 namespace gl
9 {
15 class DisjointSets {
17 public:
21  DisjointSets() = default;
26  explicit DisjointSets (idx_t numElems);
27  // other constructors
28  DisjointSets(const DisjointSets &) = default;
29  DisjointSets(DisjointSets &&) noexcept = default;
30  DisjointSets &operator=(const DisjointSets &) = default;
31  DisjointSets &operator=(DisjointSets &&) noexcept = default;
32  ~DisjointSets() = default;
33 
38  idx_t find (idx_t elem);
44  void merge (idx_t one, idx_t two);
45 
46 private:
48  std::vector<idx_t> parent_;
49  std::vector<idx_t> rank_;
50 };
51 
53 // Member function implementations
55 
57 numElems_(numElems), rank_(numElems,0), parent_(numElems) {
58  for (idx_t i = 0; i < numElems; ++i) {
59  parent_[i] = i;
60  }
61 }
62 
64  GL_ASSERT(elem < numElems_,std::string(std::string("DisjointSets::find || Element ")+std::to_string(elem)+std::string(" is larger than the max: ")+std::to_string(numElems_-1)));
65  if (elem != parent_[elem])
66  parent_[elem] = find(parent_[elem]);
67  return parent_[elem];
68 }
69 
70 void DisjointSets::merge (idx_t one, idx_t two) {
71  GL_ASSERT(one < numElems_,std::string(std::string("DisjointSets::find || Element ")+std::to_string(one)+std::string(" is larger than the max: ")+std::to_string(numElems_-1)));
72  GL_ASSERT(two < numElems_,std::string(std::string("DisjointSets::find || Element ")+std::to_string(two)+std::string(" is larger than the max: ")+std::to_string(numElems_-1)));
73 
74  one = find(one);
75  two = find(two);
76  if (rank_[one] > rank_[two]) {
77  parent_[two] = one;
78  }
79  else {
80  parent_[one] = two;
81  }
82  if (rank_[one] == rank_[two])
83  ++rank_[two];
84 }
85 
86 } // namespace gl
87 
88 #endif // GL_DISJOINT_SETS_HPP
std::vector< idx_t > rank_
Ranks of every element in their set.
Definition: DisjointSets.hpp:49
#define GL_ASSERT(EXPR, ERROR_MSG)
Custom assert that supports attaching a message.
Definition: gl_assert.hpp:14
std::size_t index_type
Definition: gl_base.hpp:18
idx_t numElems_
Initial number of sets.
Definition: DisjointSets.hpp:47
Represents disjoint sets.
Definition: DisjointSets.hpp:15
idx_t find(idx_t elem)
Finds the set parent of an element.
Definition: DisjointSets.hpp:63
gl::index_type idx_t
Definition: DisjointSets.hpp:16
DisjointSets()=default
Default constructor.
void merge(idx_t one, idx_t two)
Merges two of the disjoint sets.
Definition: DisjointSets.hpp:70
std::vector< idx_t > parent_
Parents of every element.
Definition: DisjointSets.hpp:48