题目描述
给定 n n n 个集合,第 i i i 个集合内初始状态下只有一个数,为 i i i。
有 m m m 次操作。操作分为 3 3 3 种:
-
1 a b
合并 a , b a,b a,b 所在集合; -
2 k
回到第 k k k 次操作(执行三种操作中的任意一种都记为一次操作)之后的状态; -
3 a b
询问 a , b a,b a,b 是否属于同一集合,如果是则输出1
,否则输出0
。
输入格式
第一行两个整数, n , m n,m n,m。
接下来 m m m 行,每行先输入一个数 o p t opt opt。若 o p t = 2 opt=2 opt=2 则再输入一个整数 k k k,否则再输入两个整数 a , b a,b a,b,描述一次操作。
输出格式
对每个操作 3 3 3,输出一行一个整数表示答案。
输入输出样例
输入 #1
5 6
1 1 2
3 1 2
2 0
3 1 2
2 1
3 1 2
输出 #1
1
0
1
说明/提示
对于 100 % 100\% 100% 的数据, 1 ≤ n ≤ 1 0 5 , 1 ≤ m ≤ 2 × 1 0 5 1\le n\le 10^5,1\le m\le 2\times 10^5 1≤n≤105,1≤m≤2×105。
Solution
- 模板题,可以通过 可持久化数组 + + + 启发式合并 / / / 按秩合并 实现。
Code
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=300010;
struct SegmentTree{
int lc,rc,l,r,fa,siz;
}tr[maxn*40];
int n,m,tot,root[maxn];
inline int build(int l,int r){
int u=++tot,mid=(l+r)>>1;
tr[u].l=l;tr[u].r=r;
if(l==r){tr[u].fa=l;tr[u].siz=1;return u;}
tr[u].lc=build(l,mid);
tr[u].rc=build(mid+1,r);
return u;
}
inline int query(int u,int a){
if(tr[u].l==tr[u].r)return u;
int mid=(tr[u].l+tr[u].r)>>1;
if(a<=mid)return query(tr[u].lc,a);
else return query(tr[u].rc,a);
}
inline int find(int v,int x){
int p=query(root[v],x);
return tr[p].fa==x?x:find(v,tr[p].fa);
}
inline int merge(int p,int pos,int fa){
int u=++tot;
tr[u].l=tr[p].l;tr[u].r=tr[p].r;
if(tr[u].l==tr[u].r){tr[u].fa=fa;return u;}
int mid=(tr[u].l+tr[u].r)>>1;
if(pos<=mid){
tr[u].rc=tr[p].rc;
tr[u].lc=merge(tr[p].lc,pos,fa);
}
else{
tr[u].lc=tr[p].lc;
tr[u].rc=merge(tr[p].rc,pos,fa);
}
return u;
}
inline int add(int p,int pos,int d){
int u=++tot;
tr[u].l=tr[p].l;tr[u].r=tr[p].r;
if(tr[u].l==tr[u].r){tr[u].fa=tr[p].fa;tr[u].siz=tr[p].siz+d;return u;}
int mid=(tr[u].l+tr[u].r)>>1;
if(pos<=mid){
tr[u].rc=tr[p].rc;
tr[u].lc=add(tr[p].lc,pos,d);
}
else{
tr[u].lc=tr[p].lc;
tr[u].rc=add(tr[p].rc,pos,d);
}
return u;
}
int main(){
scanf("%d%d",&n,&m);
root[0]=build(1,n);
for(int i=1;i<=m;++i){
int opt,a,b;
scanf("%d",&opt);
if(opt==1){
scanf("%d%d",&a,&b);
a=find(i-1,a);b=find(i-1,b);
if(a==b){
root[i]=root[i-1];
continue;
}
int x=query(root[i-1],a),y=query(root[i-1],b);
if(tr[x].siz>tr[y].siz)
swap(x,y),swap(a,b);
root[i]=merge(root[i-1],a,b);
root[i]=add(root[i],b,tr[x].siz);
}
else if(opt==2){
scanf("%d",&a);
root[i]=root[a];
}
else{
scanf("%d%d",&a,&b);
root[i]=root[i-1];
printf("%d\n",find(i,a)==find(i,b));
}
}
return 0;
}