数据结构 - 并查集
数据结构 - 并查集
题目链接:https://www.luogu.org/problem/P3367
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 10010;
int n, m, fa[N];
int find(int x) {
if (fa[x] == x) {
return x;
}
return fa[x] = find(fa[x]);
}
void merge(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
fa[fx] = fy;
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) {
fa[i] = i;
}
for (int i = 1; i <= m; i ++ ) {
int opt, x, y;
scanf("%d%d%d", &opt, &x, &y);
if (opt == 1) {
merge(x, y);
}
else {
if (find(x) == find(y)) {
printf("Y\n");
}
else {
printf("N\n");
}
}
}
return 0;
}