Description
n个单点集,两种操作:
1 x y:合并x和y所在集合
2 x y:合并x,x+1,…,y-1,y所在集合
3 x y:查询x和y是否在同一集合
Input
第一行两个整数n和q表示初始集合数和操作数,之后q行每行一个操作(1<=n<=2e5,1<=q<=5e5)
Output
对于每次查询操作,如果x和y属于同一集合则输出YES,否则输出NO
Sample Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Sample Output
NO
YES
YES
Solution
并查集,暴力合并显然不行,需要加个优化,令a[i]表示i集合的下一个集合编号,初始化是a[i]=i+1,那么每次点合并正常,区间合并的时候把区间[x,y]中所有点的a[i]值全部更新为a[y]的值,那么下次再合并到该区间就可以直接跳过已经合并过的这段而不是一个个合并了
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 222222
int n,q,fa[maxn],a[maxn];
void init(int n)
{
for(int i=1;i<=n;i++)fa[i]=i,a[i]=i+1;
}
int find(int x)
{
if(fa[x]==x)return x;
return fa[x]=find(fa[x]);
}
void unite(int x,int y)
{
x=find(x),y=find(y);
if(x==y)return ;
fa[x]=y;
}
int main()
{
while(~scanf("%d%d",&n,&q))
{
init(n);
while(q--)
{
int op,x,y;
scanf("%d%d%d",&op,&x,&y);
if(op==1)unite(x,y);
else if(op==2)
{
if(x>y)swap(x,y);
int temp;
for(int i=x+1;i<=y;i=temp)
{
unite(i-1,i);
temp=a[i];
a[i]=a[y];
}
}
else printf("%s\n",find(x)==find(y)?"YES":"NO");
}
}
return 0;
}