dijkstra及并查集算法更新
This commit is contained in:
36
union-find-sets.cpp
Normal file
36
union-find-sets.cpp
Normal file
@ -0,0 +1,36 @@
|
||||
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;
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user