UnionFind.h
Go to the documentation of this file.
1 // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
2 
3 // -- BEGIN LICENSE BLOCK ----------------------------------------------
4 // This file is part of FZIs ic_workspace.
5 //
6 // This program is free software licensed under the LGPL
7 // (GNU LESSER GENERAL PUBLIC LICENSE Version 3).
8 // You can find a copy of this license in LICENSE folder in the top
9 // directory of the source code.
10 //
11 // © Copyright 2016 FZI Forschungszentrum Informatik, Karlsruhe, Germany
12 //
13 // -- END LICENSE BLOCK ------------------------------------------------
14 
15 //----------------------------------------------------------------------
22 //----------------------------------------------------------------------
23 #ifndef ICL_CORE_UNION_FIND_H_INCLUDED
24 #define ICL_CORE_UNION_FIND_H_INCLUDED
25 
26 #include <vector>
27 #include <stdexcept>
28 
29 namespace icl_core {
30 
34 class UnionFind
35 {
36 public:
37  UnionFind(const std::size_t n)
38  : m_parent(n), m_rank(n, 0)
39  {
40  for (std::size_t i = 0; i < n; ++i)
41  {
42  m_parent[i] = i;
43  }
44  }
45 
47  void grow(const std::size_t n = 1)
48  {
49  std::size_t old_size = m_parent.size();
50  m_parent.resize(m_parent.size()+n);
51  m_rank.resize(m_rank.size()+n, 0);
52  for (std::size_t i = old_size; i < m_parent.size(); ++i)
53  {
54  m_parent[i] = i;
55  }
56  }
57 
61  void merge(std::size_t x, std::size_t y)
62  {
63  if (x >= m_parent.size() || y >= m_parent.size())
64  {
65  throw std::out_of_range("index out of range");
66  }
67  x = find(x);
68  y = find(y);
69  if (x == y)
70  {
71  return;
72  }
73  if (m_rank[x] < m_rank[y])
74  {
75  m_parent[x] = y;
76  }
77  else if (m_rank[x] > m_rank[y])
78  {
79  m_parent[y] = x;
80  }
81  else
82  {
83  m_parent[y] = x;
84  ++m_rank[x];
85  }
86  }
87 
88  std::size_t find(std::size_t x)
89  {
90  if (x >= m_parent.size())
91  {
92  throw std::out_of_range("index out of range");
93  }
94  if (m_parent[x] != x)
95  {
96  m_parent[x] = find(m_parent[x]);
97  }
98  return m_parent[x];
99  }
100 
101  std::size_t size() const { return m_parent.size(); }
102 
103 private:
104  std::vector<std::size_t> m_parent;
105  std::vector<std::size_t> m_rank;
106 };
107 
108 }
109 
110 #endif
void merge(std::size_t x, std::size_t y)
Definition: UnionFind.h:61
std::vector< std::size_t > m_rank
Definition: UnionFind.h:105
std::size_t find(std::size_t x)
Definition: UnionFind.h:88
UnionFind(const std::size_t n)
Definition: UnionFind.h:37
void grow(const std::size_t n=1)
Enlarges the data structure by n elements.
Definition: UnionFind.h:47
std::vector< std::size_t > m_parent
Definition: UnionFind.h:104
std::size_t size() const
Definition: UnionFind.h:101


fzi_icl_core
Author(s):
autogenerated on Mon Jun 10 2019 13:17:58