AlgoPlus v0.1.0
Loading...
Searching...
No Matches
disjoint_set.h
1#ifndef DISJOINT_SET_H
2#define DISJOINT_SET_H
3
4#ifdef __cplusplus
5#include <vector>
6#include <cstdint>
7#endif
8
13class dsu {
14 private:
15 std::vector<int64_t> p;
16 std::vector<int64_t> depth;
17 std::vector<int64_t> ssize;
18 std::vector<int64_t> max_el;
19 std::vector<int64_t> min_el;
20
21 public:
27 explicit dsu(int64_t n) {
28 p.assign(n, 0);
29 for (int64_t i = 0; i < n; i++) {
30 p[i] = i;
31 }
32 depth.assign(n, 0);
33 max_el.assign(n, 0);
34 min_el.assign(n, 0);
35 ssize.assign(n, 0);
36 for (int64_t i = 0; i < n; i++) {
37 depth[i] = 0;
38 max_el[i] = i;
39 min_el[i] = i;
40 }
41 for (int64_t i = 0; i < n; i++) {
42 ssize[i] = 1;
43 }
44 }
45
52 int64_t find(int64_t i) {
53 if (p[i] == i) {
54 return i;
55 }
56 return (p[i] = find(p[i]));
57 }
58
66 void join(int64_t i, int64_t j) {
67 if (same(i, j)) {
68 return;
69 }
70
71 int64_t x = find(i);
72 int64_t y = find(j);
73
74 if (depth[x] > depth[y]) {
75 std::swap(x, y);
76 }
77 p[x] = y;
78
79 if (depth[x] == depth[y]) {
80 depth[y]++;
81 }
82 ssize[y] += ssize[x];
83 max_el[y] = std::max(max_el[x], max_el[y]);
84 min_el[y] = std::min(min_el[x], min_el[y]);
85 }
86
95 bool same(int64_t i, int64_t j) {
96 if (find(i) == find(j)) {
97 return true;
98 }
99 return false;
100 }
101
102 std::vector<int64_t> get(int64_t i) {
103 std::vector<int64_t> ans;
104 ans.push_back(get_min(i));
105 ans.push_back(get_max(i));
106 ans.push_back(size(i));
107 return ans;
108 }
109
116 int64_t size(int64_t i) { return ssize[find(i)]; }
117
124 int64_t get_max(int64_t i) { return max_el[find(i)]; }
125
132 int64_t get_min(int64_t i) { return min_el[find(i)]; }
133};
134
135#endif
disjoint set class
Definition disjoint_set.h:13
void join(int64_t i, int64_t j)
join function
Definition disjoint_set.h:66
int64_t size(int64_t i)
size function
Definition disjoint_set.h:116
bool same(int64_t i, int64_t j)
same function
Definition disjoint_set.h:95
int64_t get_min(int64_t i)
get the minimum element of the set that i exists in
Definition disjoint_set.h:132
int64_t get_max(int64_t i)
get the maximum element of the set that i exists in
Definition disjoint_set.h:124
int64_t find(int64_t i)
find function
Definition disjoint_set.h:52
dsu(int64_t n)
Construct a new dsu object.
Definition disjoint_set.h:27