题目描述
如题,现在有一个并查集,你需要完成合并和查询操作。
输入格式
第一行包含两个整数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
说明/提示
时空限制:1000ms,128M
数据规模:
对于30%的数据,N<=10,M<=20;
对于70%的数据,N<=100,M<=1000;
对于100%的数据,N<=10000,M<=200000。
#include<cstdio>
#include<iostream>
#include<algorithm>
#define V 10003
using namespace std;
int father[V]={0};
void init(){
for(int i=0;i<V;i++) father[i]=i;
}
int find(int x){
if(father[x]==x) return x;
return father[x]=find(father[x]);
}
void merge(int x,int y){
x=find(x);y=find(y);
father[x]=y;
}
bool same(int x,int y){
return find(x)==find(y);
}
int n=0,m=0;
int main(){
ios::sync_with_stdio(false);
cin>>n>>m;
init();
for(int i=1;i<=m;i++){
int a=0,b=0,c=0;cin>>c>>a>>b;
if(c==1) merge(a,b);
else{
if(same(a,b)) cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
return 0;
}