-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdsu_rollback.cpp
More file actions
67 lines (52 loc) · 1.09 KB
/
dsu_rollback.cpp
File metadata and controls
67 lines (52 loc) · 1.09 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+123;
struct operation{
int a, b;
int rnka, rnkb;
operation(int a_, int b_, int rnka_, int rnkb_) : a(a_), b(b_), rnka(rnka_), rnkb(rnkb_) {}
};
int link[maxn];
int rnk[maxn];
int comp = 0;
stack<operation>hist;
int find(int x){
while(x != link[x]) x = link[x];
return x;
}
void unite(int a, int b){
a = find(a);
b = find(b);
if (a == b) return;
if (rnk[b] > rnk[a]) swap(a, b);
hist.push(operation(a, b, rnk[a], rnk[b]));
comp--;
link[b] = a;
if (rnk[a] == rnk[b]) rnk[a]++;
}
void rollback(){
if (hist.empty()) return;
operation op = hist.top();
hist.pop();
link[op.a] = op.a;
link[op.b] = op.b;
rnk[op.a] = op.rnka;
rnk[op.b] = op.rnkb;
comp++;
}
int main(){
int n = 10;
comp = n;
for(int i = 1;i <= n;i++) link[i] = i;
unite(1, 2);
cout << comp << endl;
unite(3, 4);
cout << comp << endl;
unite(1, 3);
cout << comp << endl;
rollback();
rollback();
rollback();
cout << comp << endl;
return 0;
}