- BC20280018's blog
并查集模板
- 2025-9-13 15:36:30 @
并查集模板
题目描述
如题,现在有一个并查集,你需要完成合并和查询操作。
输入格式
第一行包含两个整数 ,表示共有 个元素和 个操作。
接下来 行,每行包含三个整数 。
当 时,将 与 所在的集合合并。
当 时,输出 与 是否在同一集合内,是的输出
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
说明/提示
对于 的数据,,。
对于 的数据,,。
对于 的数据,,。
对于 的数据,,,,。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+5;
int fa[N];
int n, m, op, x, y;
int find(int x)
{
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
fa[i] = i;
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &op, &x, &y);
if(op == 1)
{
x = find(x), y = find(y);
if(x == y)
continue;
fa[x] = y;
}
else
{
x = find(x), y = find(y);
if(x == y)
printf("Y\n");
else
printf("N\n");
}
}
return 0;
}