解题思路:并查集模板,需要路径压缩进行优化,否则会超时,这个题目只要路径优化后就可以过,路径压缩和按秩合并如果一起使用,时间复杂度接近o(n) ,但是很可能会破坏rank的准确性
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
#include <set>
#include <map>
#define dbg(a) cout<<#a<<" : "<<a<<endl;
using namespace std;
typedef long long ll;
ll fa[200005];
ll find(ll x)
{
if(fa[x]==x)
return x;
else{
fa[x]=find(fa[x]); //父节点设为根节点
return fa[x]; //返回父节点
}
}
void merge(int i,int j)
{
fa[find(i)]=find(j);
}
void init(ll n)
{
for(ll i=1;i<=n;i++)
{
fa[i]=i;
}
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
ll n,m;
ll z,x,y;
cin>>n>>m;
init(n);
for(ll i=1;i<=m;i++)
{
cin>>z>>x>>y;
if(z==1){
merge(x,y);
}else{
if(find(x)==find(y))
cout<<"Y"<<endl;
else
cout<<"N"<<endl;
}
}
return 0;
}