aboutsummaryrefslogtreecommitdiffstats
path: root/meowpp/dsa/DisjointSet.hpp
blob: 3b66626e73511664ba434789db32cfbe0a0f17c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <vector>
#include <cstdlib>

namespace meow{
  inline size_t DisjointSet::_root(size_t now){
    if(father[now] == now) return now;
    return (father[now] = _root(father[now]));
  }
  inline size_t DisjointSet::_merge(size_t a, size_t b){
    a = _root(a);
    b = _root(b);
    if(a == b) return a;
    if(depth[a] > depth[b]){
      father[b] = a;
      return a;
    }else{
      father[a] = b;
      if(depth[a] == depth[b]){
        depth[b]++;
      }
      return b;
    }
  }
  //
  inline DisjointSet::DisjointSet(): n(0){ }
  inline DisjointSet::DisjointSet(size_t _n): n(0){
    reset(_n);
  }
  inline DisjointSet::DisjointSet(DisjointSet const& dsj){
    n      = dsj.n;
    father = dsj.father;
    depth  = dsj.depth;
  }
  //
  inline size_t DisjointSet::root(size_t a) const{
    return ((DisjointSet*)this)->_root(a);
  }
  inline size_t DisjointSet::size() const{ return n; }
  //
  inline void DisjointSet::reset(size_t _n){
    n = _n;
    father.resize(n);
    depth .resize(n);
    for(size_t i = 0; i < n; i++){
      father[i] = i;
      depth [i] = 1;
    }
  }
  inline size_t DisjointSet::merge(size_t a, size_t b){
    return _merge(a, b);
  }
}