题目描述
如题,现在有一个并查集,你需要完成合并和查询操作。
输入格式
第一行包含两个整数 N,M ,表示共有 N 个元素和 M 个操作。
接下来 M 行,每行包含三个整数 Zi,Xi,Yi 。
当Zi=1 时,将 Xi 与 Yi 所在的集合合并。
当 Zi=2 时,输出 Xi 与 Yi 是否在同一集合内,是的输出 Y
;否则输出 N
。
输出格式
对于每一个 Zi=2 的操作,都有一行输出,每行包含一个大写字母,为 Y
或者 N
。
输入输出样例
输入 #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>
#define fi first
#define se second
#define pb push_back
#define PII pair<int,int >
#define int long long
#define IOS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
using namespace std;
const int N = 1e6+10;
int n,m;
int acc[N];
int find(int x)
{
if(x!=acc[x]) acc[x]=find(acc[x]);
return acc[x];
}
signed main()
{
IOS;
cin>>n>>m;
for(int i=1;i<=n;i++) acc[i]=i;
for(int i=1;i<=m;i++)
{
int op,a,b;
cin>>op>>a>>b;
if(op==1)
{
int t1=find(a),t2=find(b);
if(t1!=t2) acc[t1]=t2;
}
else
{
int t1=find(a),t2=find(b);
if(t1==t2)
{
cout<<"Y"<<"\n";
}
else
{
cout<<"N"<<"\n";
}
}
}
return 0;
}