36 lines
633 B
C++
36 lines
633 B
C++
class UnionFind {
|
|
vector<int> _pre; // 代表元
|
|
vector<int> _rank; // 集合的秩
|
|
|
|
public:
|
|
UnionFind(int n) : _pre(n), _rank(n, 1) {
|
|
iota(_pre.begin(), _pre.end(), 0);
|
|
//ranges::iota(_pre, 0);
|
|
}
|
|
|
|
int find(int x) {
|
|
return _pre[x] == x ? x : _pre[x] = find(_pre[x]);
|
|
}
|
|
|
|
bool same(int x, int y) {
|
|
return find(x) == find(y);
|
|
}
|
|
|
|
bool merge(int from, int to) {
|
|
int x = find(from), y = find(to);
|
|
if (x == y) {
|
|
return false;
|
|
}
|
|
if (_rank[x] < _rank[y]) {
|
|
_pre[x] = y;
|
|
}
|
|
else if (_rank[x] > _rank[y]) {
|
|
_pre[y] = x;
|
|
}
|
|
else {
|
|
_pre[x] = y;
|
|
_rank[y]++;
|
|
}
|
|
return true;
|
|
}
|
|
}; |