Disjoint Set Union
同时使用了路径压缩 + 启发式合并后,时间复杂度为 \(O(\alpha(n))\),阿卡曼反函数
任意一个单独使用,时间复杂度为 \(O(nlogn)\)
https://www.luogu.com.cn/problem/P3367
#include<bits/stdc++.h>
using namespace std;
using LL = long long;
struct DSU{
vector<int> p, siz;
DSU(int n){
p.resize(n + 1);
iota(p.begin(), p.end(), 0);
siz.assign(n + 1, 1);
}
int get(int x){
return x == p[x] ? x : (p[x] = get(p[x]));
}
bool same(int x, int y){
return get(x) == get(y);
}
bool unite(int x, int y){
x = get(x);
y = get(y);
if (x == y){
return false;
}
if (x < y) swap(x, y);
siz[x] += siz[y];
p[y] = x;
return true;
}
int size(int x) {
return siz[get(x)];
}
};
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int n, m;
cin >> n >> m;
DSU d(n);
for (int i = 0; i < m; i ++ ){
int op, x, y;
cin >> op >> x >> y;
if (op == 1){
d.unite(x, y);
}
else{
if (d.get(d.p[x]) == d.get(d.p[y])){
cout << "Y\n";
}
else{
cout << "N\n";
}
}
}
return 0;
}