【模板】并查集
题目描述
如题,现在有一个并查集,你需要完成合并和查询操作。
输入格式
第一行包含两个整数
接下来
当
当 Y ;否则输出 N 。
输出格式
对于每一个 Y 或者 N 。
样例 #1
样例输入 #1
4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4样例输出 #1
N
Y
N
Y提示
对于
对于
对于
路径压缩:查询过程中经过的每个元素都属于该集合,直接将其连接到根节点加快后续查询、
题解
c++
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct DSU {
vector<int> f, siz;
DSU() {}
DSU(int n) { init(n); }
void init(int n) {
f.resize(n);
iota(f.begin(), f.end(), 0);
siz.assign(n, 1);
}
int find(int x) {
while (x != f[x]) {
x = f[x] = f[f[x]];
}
return x;
}
bool same(int x, int y) { return find(x) == find(y); }
bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) { return siz[find(x)]; }
};
void solve() {
int n, m;
cin >> n >> m;
DSU dsu(n + 1);//节点编号从1开始 需要多分配一个空间
for (int i = 1; i <= m; i++) {
int z, x, y;
cin >> z >> x >> y;
if (z == 1) {
dsu.merge(x, y);
} else {
if (dsu.same(x, y)) {
cout << "Y\n";
} else {
cout << "N\n";
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}维护到祖宗节点距离的并查集
c++
int p[N],d[N];
//p[]存储每个节点的祖宗结点,d[x]存储x到p[x]的距离
int find(int x){
if(p[x]!=x){
int u=find(p[x]);
d[x]+=d[p[x]];
p[x]=u;
}
return p[x];
}
//初始化
for(int i=1;i<=n;i++){
p[i]=i;
d[i]=0;
}
//合并a、b两个集合
p[find(a)]=find(b);
d[find(a)]=distance;//板子
c++
struct DSU {
std::vector<int> f, siz;
DSU() {}
DSU(int n) { init(n); }
void init(int n) {
f.resize(n);
std::iota(f.begin(), f.end(), 0);
siz.assign(n, 1);
}
int find(int x) {
while (x != f[x]) {
x = f[x] = f[f[x]];
}
return x;
}
bool same(int x, int y) { return find(x) == find(y); }
bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (siz[x] < siz[y]) {
std::swap(x, y);
}
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) { return siz[find(x)]; }
};DSU() {}的作用
如果没有这段代码,那么DSU(int n)是唯一的构造函数
c++
DSU dsu;//这样写会编译错误 因为没有默认构造函数但是有了DSU() {};就可以合法创建空的DSU对象,配合init(n)进行初始化
DSU dsu;
dsu.init(10);这样可以先创建DSU对象,再根据需要初始化大小,提高灵活性
如果想先创建,在初始化,就需要DSU()这个默认构造函数