JiangMzz @ 2024-08-10 18:18:45
#include <bits/stdc++.h>
using namespace std;
int n, m;
int f[10001];
int find(int x) {
if (f[x] == x) return x;
return f[x] = find(f[x]);
}
void join(int x, int y) {
if (find(x) != find(y)) f[x] = y;
return;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
f[i] = i;
rank[i] = 1;
}
for (int i = 1; i <= m; i++) {
int opt, x, y;
cin >> opt >> x >> y;
if (opt == 1) {
join(x, y);
}
else {
int fx = find(x);
int fy = find(y);
if (fx == fy)
cout << "Y" << endl;
else
cout << "N" << endl;
}
}
return 0;
}
by Michaellg @ 2024-08-10 18:23:58
@JiangMzz 把 join
函数改成 f[find(x)] = find(y);
就可以了
by JiangMzz @ 2024-08-10 18:44:08
@Michaellg 把``` f[x] = y;
改成```
f[find(x)] = find(y);
还是整个join函数改成这一句啊?还有本蒟蒻不懂为什么【捂脸】求大佬讲解
by Michaellg @ 2024-08-10 18:50:49
@JiangMzz 都可以。
这句就是把 x 所在的并查集的根合并到 y 所在的并查集的根。
如果 find(x)=find(y)
,这句相当于 f[rt]=rt
(rt=find(x)
),对结果没有影响。
如果还不理解可以看 https://oi-wiki.org/ds/dsu/。
by JiangMzz @ 2024-08-10 19:25:41
@Michaellg 已关,谢谢大佬!!AC了!