#include
#include
#include
#include
using namespace std;
const int maxn=2e5+10;
int pre[maxn];
int nex[maxn];
int n,q;
int foot1,foot2;
int a,b;
void init()
{
for(int i=0; i<=n+3; ++i)
{
pre[i]=i;
nex[i]=i+1;
}
}
int finds(int x)
{
if(x==pre[x])
return x;
pre[x]=finds(pre[x]);
return pre[x];
}
void unions(int x,int y)
{
foot1=finds(x);
foot2=finds(y);
if(foot2!=foot1)
{
pre[foot1]=foot2;
return;
}
return;
}
int type;
int main()
{
int to;
scanf("%d%d",&n,&q);
init();
while(q--)
{
scanf("%d%d%d",&type,&a,&b);
if(type==1)
{
if(finds(a)!=finds(b))
unions(a,b);
}
else if(type==2)
{
for(int i=a+1; i<=b; i=to)
{
unions(i-1,i);
to=nex[i];
nex[i]=nex[b];
}
}
else
{
foot1=finds(a);
foot2=finds(b);
if(foot1!=foot2)
printf("NO\n");
else
printf("YES\n");
}
}
return 0;
}
并查集区间合并更新优化代码如下:
else if(type==2)
{
for(int i=a+1; i<=b; i=to)
{
unions(i-1,i);
to=nex[i];
nex[i]=nex[b];
}
}
用nex[maxn]数组索引,这种思想可以普遍应用于并查集区间合并优化。