UnionFind.cpp
Go to the documentation of this file.
1 #include "UnionFind.h"
2 
3 #include <cstddef>
4 
6 {
7  UnionFind::UnionFind(std::size_t n)
8  {
9  rank.reserve(n);
10  parent.reserve(n);
11  for (std::size_t i = 0; i < n; i++)
12  {
13  rank.push_back(0);
14  parent.push_back(i);
15  }
16  }
17 
18  std::size_t
19  UnionFind::find(std::size_t x)
20  {
21  // Finds the representative of the set
22  // that x is an element of
23  if (parent[x] != x)
24  {
25 
26  // if x is not the parent of itself
27  // Then x is not the representative of
28  // his set,
29  parent[x] = find(parent[x]);
30 
31  // so we recursively call Find on its parent
32  // and move i's node directly under the
33  // representative of this set
34  }
35 
36  return parent[x];
37  }
38 
39  void
40  UnionFind::unite(std::size_t a, std::size_t b)
41  {
42  // Find current sets of x and y
43  std::size_t xset = find(a);
44  std::size_t yset = find(b);
45 
46  // If they are already in same set
47  if (xset == yset)
48  return;
49 
50  // Put smaller ranked item under
51  // bigger ranked item if ranks are
52  // different
53  if (rank[xset] < rank[yset])
54  {
55  parent[xset] = yset;
56  }
57  else if (rank[xset] > rank[yset])
58  {
59  parent[yset] = xset;
60  }
61 
62  // If ranks are same, then increment
63  // rank.
64  else
65  {
66  parent[yset] = xset;
67  rank[xset] = rank[xset] + 1;
68  }
69  }
70 
71 
72 } // namespace armarx::navigation::components::laser_scanner_feature_extraction
UnionFind.h
armarx::navigation::components::laser_scanner_feature_extraction::UnionFind::unite
void unite(std::size_t a, std::size_t b)
unite the sets of the elements a and b
Definition: UnionFind.cpp:40
armarx::ctrlutil::a
double a(double t, double a0, double j)
Definition: CtrlUtil.h:45
armarx::navigation::components::laser_scanner_feature_extraction
Definition: ArVizDrawer.cpp:28
armarx::navigation::components::laser_scanner_feature_extraction::UnionFind::UnionFind
UnionFind(std::size_t n)
Construct a new union find data structure with n elements.
Definition: UnionFind.cpp:7
armarx::navigation::components::laser_scanner_feature_extraction::UnionFind::find
std::size_t find(std::size_t x)
find the representative of x
Definition: UnionFind.cpp:19