CodeForces 566D 并查集集合合并

时间:2023-03-08 16:50:18
 #include <stdio.h>
#include <algorithm>
#define MAX 100000
#define LL long long
#define unsigned U
//using namespace std;
int cas=,T;
int fa[MAX*+],next[MAX*+],n,q;
void init(int n)
{
for(int i=;i<=n;i++) { fa[i]=i;next[i]=i+; }
}
int find(int x)
{
return fa[x]==x?x:(fa[x]=find(fa[x]));
}
void merge(int x,int y)
{
if(x>y) std::swap(x,y);
for(int i=x+;i<=y;)
{
int xx=find(i);
int yy=find(i-);
fa[xx]=fa[yy]=std::min(xx,yy);
int tmp=next[i];
next[i]=next[y];
i=tmp;
}
}
int main()
{
//freopen("1.in","w",stdout);
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
//scanf("%d",&T);
while(scanf("%d%d",&n,&q)==)
{
init(n);
int t,x,y;
while(q--)
{
scanf("%d%d%d",&t,&x,&y);
if(t==) puts(find(x)==find(y)?"YES":"NO");
else if(t==) merge(x,y);
else
{
int xx=find(x);
int yy=find(y);
fa[xx]=fa[yy]=std::min(xx,yy);
}
}
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return ;
}