-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnionFind.cpp
96 lines (92 loc) · 2.35 KB
/
UnionFind.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
// if par is negative, it is a root, of which tree size is the abs-value.
// rank represents depth
class UnionFind {
public:
vector<int> par, rank;
UnionFind(int sz) : par(sz, -1), rank(sz, 0){}
int find(int x){
if(par[x]<0) return x;
else return par[x] = find(par[x]);
}
void unite(int x, int y){
x=find(x); y=find(y);
if(x==y) return;
if(rank[x] < rank[y]) swap(x,y);
par[x] += par[y];
par[y] = x;
if(rank[x]==rank[y]) rank[x]++;
}
inline bool same(int x, int y){ return find(x) == find(y); }
inline int size(int x){ return -par[find(x)]; }
inline bool isroot(int x) const { return par[x] < 0; }
};
template <class T>
class WeightedUnionFind {
int n;
vector<int> par,sz;
vector<T> w;
// weight[i] : iがpar[i]よりどれだけ重いか
public:
WeightedUnionFind(){}
WeightedUnionFind(int _n) : n(_n) {
par.resize(n, -1);
sz.resize(n, 1);
w.resize(n, 0);
}
int find(int i){
if(par[i] < 0) return i;
int p = find(par[i]);
w[i] += w[par[i]];
return par[i] = p;
}
T weight(int x){ find(x); return w[x]; }
bool same(int x, int y){ return find(x) == find(y); }
// weight[i] +w の位置に j を配置
void unite(int i, int j, T nw){
nw += weight(i) - weight(j);
int x = find(i), y = find(j);
if(x == y) return;
if(sz[x] < sz[y]){
swap(x, y);
nw = -nw;
}
sz[x] += sz[y];
par[y] = x;
w[y] = nw;
}
// x からみた y の相対位置
T diff(int x, int y){ return weight(y) - weight(x); }
};
class RewindableUnionFind {
public:
vector<int> par, rank;
vector<pair<int,pair<int,int>>> history; // <idx, <par, rank>>
RewindableUnionFind(int sz) : par(sz, -1), rank(sz, 0){}
int find(int x){
if(par[x]<0) return x;
else return find(par[x]);
}
void record(int x){
history.pb(mp(x,mp(par[x],rank[x])));
}
void rewind(){
assert(history.size()>=2);
rep(_,2){
auto &pp = history.back();
par[pp.fi] = pp.se.fi;
rank[pp.fi] = pp.se.se;
history.pop_back();
}
}
void unite(int x, int y){
x = find(x); y = find(y);
record(x); record(y);
if(x==y) return;
if(rank[x] < rank[y]) swap(x,y);
par[x] += par[y];
par[y] = x;
if(rank[x]==rank[y]) rank[x]++;
}
inline bool same(int x, int y){ return find(x) == find(y); }
inline int size(int x){ return -par[find(x)]; }
};