Open
Graph Drawing
Framework

 v. 2023.09 (Elderberry)
 

UnionFind.h
Go to the documentation of this file.
1 
31 #pragma once
32 
33 #include <ogdf/basic/basic.h>
34 
35 #include <vector>
36 
37 namespace ogdf {
38 namespace internal {
39 namespace gcm {
40 namespace datastructure {
41 
45 class UnionFind {
46 private:
47  std::vector<int> data;
48 
49 public:
55  UnionFind(unsigned int max_element) : data(max_element) { all_to_singletons(); }
56 
63  void all_to_singletons() { data.assign(data.size(), -1); }
64 
70  unsigned int find(unsigned int u) {
71  OGDF_ASSERT(u < data.size());
72  if (data[u] >= 0) {
73  data[u] = find(data[u]);
74  return data[u];
75  } else {
76  return u;
77  }
78  }
79 
80  unsigned int operator[](unsigned int u) { return find(u); }
81 
87  void merge(unsigned int u, unsigned int v) {
88  unsigned int set_u = find(u);
89  unsigned int set_v = find(v);
90  if (set_u == set_v) {
91  return;
92  }
93 
94  if (data[set_u] > data[set_v]) {
95  data[set_u] = set_v;
96  } else if (data[set_v] > data[set_u]) {
97  data[set_v] = set_u;
98  } else {
99  data[set_u] = set_v;
100  --data[set_v];
101  }
102  }
103 };
104 }
105 }
106 }
107 }
ogdf
The namespace for all OGDF objects.
Definition: multilevelmixer.cpp:39
ogdf::internal::gcm::datastructure::UnionFind::find
unsigned int find(unsigned int u)
Find the representative to element u.
Definition: UnionFind.h:70
ogdf::internal::gcm::datastructure::UnionFind::merge
void merge(unsigned int u, unsigned int v)
Merge the two sets containing u and v.
Definition: UnionFind.h:87
OGDF_ASSERT
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:66
ogdf::internal::gcm::datastructure::UnionFind::UnionFind
UnionFind(unsigned int max_element)
Create a new set representation with not more than max_element elements.
Definition: UnionFind.h:55
ogdf::internal::gcm::datastructure::UnionFind
Implements the Union Find Datastructure to maintain disjoint sets efficiently.
Definition: UnionFind.h:45
ogdf::internal::gcm::datastructure::UnionFind::operator[]
unsigned int operator[](unsigned int u)
Definition: UnionFind.h:80
ogdf::internal::gcm::datastructure::UnionFind::all_to_singletons
void all_to_singletons()
Assigns every element to a singleton set.
Definition: UnionFind.h:63
basic.h
Basic declarations, included by all source files.
ogdf::internal::gcm::datastructure::UnionFind::data
std::vector< int > data
Definition: UnionFind.h:47