forked from ifsmirnov/jngen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsu.h
68 lines (48 loc) · 1.07 KB
/
dsu.h
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#pragma once
#include <algorithm>
#include <vector>
namespace jngen {
class Dsu {
public:
int getRoot(int x);
bool unite(int x, int y);
bool isConnected() const { return components <= 1; }
int numComponents() const { return components; }
void extend(size_t size);
private:
std::vector<int> parent;
std::vector<int> rank;
int components = 0;
};
#ifndef JNGEN_DECLARE_ONLY
int Dsu::getRoot(int x) {
extend(x);
return parent[x] == x ? x : (parent[x] = getRoot(parent[x]));
}
bool Dsu::unite(int x, int y) {
extend(std::max(x, y) + 1);
x = getRoot(x);
y = getRoot(y);
if (x == y) {
return false;
}
if (rank[x] > rank[y]) {
std::swap(x, y);
}
if (rank[y] == rank[x]) {
++rank[y];
}
parent[x] = y;
--components;
return true;
}
void Dsu::extend(size_t x) {
size_t last = parent.size() - 1;
while (parent.size() < x) {
++components;
parent.push_back(++last);
rank.push_back(0);
}
}
#endif // JNGEN_DECLARE_ONLY
} // namespace jngen