P3367 并查集【模板】 题解
思路:创立一个数组来记录这个元素的大哥,一开始的元素的大哥都是自己,当两个元素需要合并时,两个元素大哥设为相同的数,这时就可以认定他们两个元素已经合并了。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <map>
#include <queue>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn=200000;
int n,m,father[maxn];
int bing(int x) //合并两个元素
{
return father[x] == x ? x : father[x]=bing(father[x]);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++){
father[i]=i;
}
for(int i=0;i<m;i++){
int z,x,y;
scanf("%d%d%d",&z,&x,&y);
if(z==2){
if(bing(x)==bing(y)) printf("Y\n"); //判断两个元素的大哥是否相同
else printf("N\n");
}
else{
father[bing(x)]=bing(y);
}
}
return 0;
}