Templates -- Meow  1.1.2
不能,也不應該先編譯成obj-file的templates
DisjointSet.h
Go to the documentation of this file.
1 #ifndef dsa_DisjointSet_H__
2 #define dsa_DisjointSet_H__
3 
4 #include <vector>
5 #include <cstdlib>
6 #include <cstdio>
7 
8 namespace meow {
25 class DisjointSet {
26 private:
27  size_t n_;
28  std::vector<size_t> father_;
29  std::vector<size_t> depth_;
30  //
31  size_t root_(size_t now) {
32  if (father_[now] == now) return now;
33  return (father_[now] = root_(father_[now]));
34  }
35 
36  size_t merge_(size_t a, size_t b) {
37  a = root_(a);
38  b = root_(b);
39  if (a == b) return a;
40  if (depth_[a] > depth_[b]) {
41  father_[b] = a;
42  return a;
43  }
44  else {
45  father_[a] = b;
46  if (depth_[a] == depth_[b]) depth_[b]++;
47  return b;
48  }
49  }
50 public:
54  DisjointSet(): n_(0) {
55  }
56 
62  DisjointSet(size_t n) {
63  reset(n);
64  }
65 
73  DisjointSet(DisjointSet const& dsj):
74  n_(dsj.n_), father_(dsj.father_), depth_(dsj.depth_) {
75  }
76 
85  size_t root(size_t a) const {
86  return ((DisjointSet*)this)->root_(a);
87  }
88 
89 
95  size_t size() const {
96  return n_;
97  }
98 
107  void reset(size_t n) {
108  n_ = n;
109  father_.resize(n);
110  depth_ .resize(n);
111  for (size_t i = 0; i < n; i++) {
112  father_[i] = i;
113  depth_ [i] = 1;
114  }
115  }
116 
128  size_t merge(size_t a, size_t b) {
129  return merge_(a, b);
130  }
131 };
132 
133 }
134 
135 #endif // dsa_DisjointSet_H__