Hello all. I am trying out this problem on CodeChef.
I am using Disjoint Set along with path compression and union by rank. Still I am getting TLE. Please suggest the changes I should incorporate. Here is my code.
#include <iostream>
using namespace std;
typedef long long ll;
struct DisjointSet
{
ll *rank, *parent;
DisjointSet(ll N){
rank=new ll[N+1];
parent=new ll[N+1];
for(ll i=0;i<=N;i++)
{
rank[i]=1;
parent[i]=i;
}
}
ll find(ll x){
if(parent[x]!=x){
parent[x]=find(parent[x]);
}
return parent[x];
}
void union_rank(ll a,ll b){
ll pa=find(a);
ll pb=find(b);
if(pa==pb)
return;
if(rank[pa] > rank[pb])
{
parent[pb]=pa;
rank[pa]+=rank[pb];
}
else {
parent[pa]=pb;
rank[pb]+=rank[pa];
}
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll tc;
cin>>tc;
while(tc--)
{
ll N,M;
cin>>N>>M;
DisjointSet d(N);
for(int i=0;i<M;i++)
{
ll q,x,y;
cin>>q>>x>>y;
if(q==1){
d.union_rank(x,y);
}
else
{
if(d.find(x)==d.find(y)){
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
}
}



