WTFIT
UnionFind.h
Go to the documentation of this file.
1 
8 #ifndef _UNION_FIND_H
9 #define _UNION_FIND_H
10 
11 #include <Debug.h>
12 
13 #include <algorithm>
14 #include <vector>
15 
16 using namespace std;
17 
18 namespace wtfit{
19 
20  class UnionFind : virtual public Debug{
21 
22 
23  public:
24 
25  // 1) constructors, destructors, operators
26  inline UnionFind();
27 
28  inline UnionFind(const UnionFind &other);
29 
30  inline bool operator<(const UnionFind &other) const{
31  return rank_ < other.rank_;
32 
33  };
34 
35  inline bool operator>(const UnionFind &other) const{
36  return rank_ > other.rank_;
37 
38  };
39 
40  // 2) functions
41  inline UnionFind* find();
42 
43  inline int getRank() const { return rank_;};
44 
45  static inline UnionFind* makeUnion(vector<UnionFind *> &sets);
46 
47  inline void setParent(UnionFind *parent){ parent_ = parent;};
48 
49  inline void setRank(const int &rank) { rank_ = rank;};
50 
51 
52  protected:
53 
54 
55  int rank_;
57 
58  };
59 
60  inline UnionFind::UnionFind(){
61 
62  rank_ = 0;
63  parent_ = this;
64  }
65 
66  inline UnionFind::UnionFind(const UnionFind &other){
67 
68  rank_ = other.rank_;
69  parent_ = this;
70  }
71 
72  inline UnionFind* UnionFind::find(){
73 
74  if(parent_ == this)
75  return this;
76  else{
77  parent_ = parent_->find();
78  return parent_;
79  }
80  }
81 
82  static inline UnionFind* makeUnion(UnionFind *uf0, UnionFind *uf1){
83 
84  uf0 = uf0->find();
85  uf1 = uf1->find();
86 
87  if(uf0 == uf1){
88  return uf0;
89  }
90  else if(uf0->getRank() > uf1->getRank()){
91  uf1->setParent(uf0);
92  return uf0;
93  }
94  else if(uf0->getRank() < uf1->getRank()){
95  uf0->setParent(uf1);
96  return uf1;
97  }
98  else{
99  uf1->setParent(uf0);
100  uf0->setRank(uf0->getRank() + 1);
101  return uf0;
102  }
103 
104  return NULL;
105  }
106 
107  static inline UnionFind* makeUnion(vector<UnionFind *> &sets){
108 
109  UnionFind *n = NULL;
110 
111  if(!sets.size()) return NULL;
112 
113  if(sets.size() == 1) return sets[0];
114 
115  for(int i = 0; i < (int) sets.size() - 1; i++)
116  n = makeUnion(sets[i], sets[i + 1]);
117 
118  return n;
119  }
120 
121 }
122 
123 #endif
Union Find implementation for connectivity tracking.
Definition: UnionFind.h:20
int rank_
Definition: UnionFind.h:49
bool operator<(const UnionFind &other) const
Definition: UnionFind.h:30
int getRank() const
Definition: UnionFind.h:43
bool operator>(const UnionFind &other) const
Definition: UnionFind.h:35
UnionFind * parent_
Definition: UnionFind.h:56
void setRank(const int &rank)
Definition: UnionFind.h:49
Minimalist debugging class.
Definition: Debug.h:39
Definition: CommandLineParser.h:13
UnionFind * find()
Definition: UnionFind.h:72
void setParent(UnionFind *parent)
Definition: UnionFind.h:47