P3367 【模板】并查集
思路
模板题目
参考代码:
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 7;
int fa[maxn];
int find(int x) // 查找 酷炫写法
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
// int find(int x) // 查找 展开写法
// {
// if (x == fa[x]) return x;
// int root = find(fa[x]);
// return fa[x] = root;
// }
void merge(int x, int y)
{
x = find(x), y = find(y);
if (x != y) fa[x] = y;
}
signed main()
{
std::ios::sync_with_stdio(false);
std::cout.tie(0);
std::cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--)
{
int op, x, y;
cin >> op >> x >> y;
if (op == 1) merge(x, y);
else {
x = find(x), y = find(y);
if (x != y) cout << "N" << endl;
else cout << "Y" << endl;
}
}
return 0;
}