-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjoint_set_union.cpp
104 lines (83 loc) · 2.21 KB
/
disjoint_set_union.cpp
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class DisjointSetUnion {
private:
vector<int> ancestor_;
vector<int> sizes_;
size_t components_count_ = 0;
public:
inline int Find(int a) {
return (ancestor_[a] == a) ? a : ancestor_[a] = Find(ancestor_[a]);
}
bool Unite(int a, int b) {
if (IsConnected(a, b))
return false;
a = Find(a);
b = Find(b);
if (sizes_[a] > sizes_[b])
swap(a, b);
ancestor_[a] = b;
sizes_[b] += sizes_[a];
--components_count_;
return true;
}
inline bool IsConnected(int a, int b) { return Find(a) == Find(b); }
inline int GetComponentsCount() const { return components_count_; }
DisjointSetUnion(int n)
: sizes_(vector<int>(n + 1, 1))
, components_count_(n) {
++n;
ancestor_.resize(n);
for (int i = 0; i < n; i++)
ancestor_[i] = i;
}
};
class DSUWithRollback {
private:
vector<int> ancestor_;
vector<int> sizes_;
size_t components_count_ = 0;
struct Query {
int u, v;
char changed_something;
};
vector<Query> queries_;
public:
DSUWithRollback(int n)
: sizes_(vector<int>(n + 1, 1))
, components_count_(n) {
++n;
ancestor_.resize(n);
for (int i = 0; i < n; i++)
ancestor_[i] = i;
}
inline int Find(int a) {
return (ancestor_[a] == a) ? a : Find(ancestor_[a]);
}
bool Unite(int a, int b) {
a = Find(a);
b = Find(b);
if (sizes_[a] > sizes_[b]) {
swap(a, b);
}
queries_.push_back({a, b, a != b});
if (a == b) {
return false;
}
ancestor_[a] = b;
sizes_[b] += sizes_[a];
--components_count_;
return true;
}
void Revert() {
if (queries_.empty())
return;
Query query = queries_.back();
queries_.pop_back();
if (query.changed_something) {
sizes_[query.u] -= sizes_[query.v];
ancestor_[query.u] = query.u;
++components_count_;
}
}
inline bool IsConnected(int a, int b) { return Find(a) == Find(b); }
inline int GetComponentsCount() const { return components_count_; }
};