-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSU.cpp
More file actions
52 lines (47 loc) · 1 KB
/
DSU.cpp
File metadata and controls
52 lines (47 loc) · 1 KB
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
struct dsu {
vector<int> hist, par, sz;
vector<ii> changes;
int n;
dsu (int n) : n(n) {
hist.assign(n, 1e9);
par.resize(n);
iota(par.begin(), par.end(), 0);
sz.assign(n, 1);
}
int root (int x, int t) {
if(hist[x] > t) return x;
return root(par[x], t);
}
void join (int a, int b, int t) {
a = root(a, t);
b = root(b, t);
if (a == b) { changes.emplace_back(-1, -1); return; }
if (sz[a] > sz[b]) swap(a, b);
par[a] = b;
sz[b] += sz[a];
hist[a] = t;
changes.emplace_back(a, b);
n--;
}
bool same (int a, int b, int t) {
return root(a, t) == root(b, t);
}
void undo () {
int a, b;
tie(a, b) = changes.back();
changes.pop_back();
if (a == -1) return;
sz[b] -= sz[a];
par[a] = a;
hist[a] = 1e9;
n++;
}
int when (int a, int b) {
while (1) {
if (hist[a] > hist[b]) swap(a, b);
if (par[a] == b) return hist[a];
if (hist[a] == 1e9) return 1e9;
a = par[a];
}
}
};