1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include <bits/stdc++.h>
#define debug freopen("in.txt","r",stdin); freopen("out.txt","w",stdout) #define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) using namespace std; typedef long long ll; typedef unsigned long long ull; const int MAXN=1e6+100; const int MOD=1e9+7; const int INF=0x3f3f3f3f; const int SUB=-0x3f3f3f3f; const double eps=1e-4; const double E=exp(1); const double pi=acos(-1); struct node{ int ls,rs,val; }fa[MAXN*40]; int dep[MAXN*40],rt[MAXN*40]; int n,m,op,a,b,tot,k; int build(int l,int r){ int root=++tot; if(l==r){ fa[root].val=l; return root; } int mid=(l+r)>>1; fa[root].ls=build(l,mid); fa[root].rs=build(mid+1,r); return root; } int query(int nod,int l,int r,int x){ if(l==r) return nod; int mid=l+r>>1; if(x<=mid) return query(fa[nod].ls,l,mid,x); else return query(fa[nod].rs,mid+1,r,x); } int find(int nod,int x){ int now=query(nod,1,n,x); if(fa[now].val==x) return now; return find(nod,fa[now].val); } int remerge(int pre,int l,int r,int x,int y){ int root=++tot; fa[root]=fa[pre]; if(l==r){ fa[root].val=y; return root; } int mid=l+r>>1; if(x<=mid) fa[root].ls=remerge(fa[pre].ls,l,mid,x,y); else fa[root].rs=remerge(fa[pre].rs,mid+1,r,x,y); return root; } int main(){ ios; cin>>n>>m; rt[0]=build(1,n); for(int i=1;i<=m;i++){ cin>>op; if(op==1){ cin>>a>>b; rt[i]=rt[i-1]; int x=find(rt[i],a),y=find(rt[i],b); if(fa[x].val!=fa[y].val){ if(dep[x]>dep[y]) swap(x,y); rt[i]=remerge(rt[i-1],1,n,fa[x].val,fa[y].val); if(dep[x]==dep[y]) dep[y]++; } } else if(op==2){ cin>>k; rt[i]=rt[k]; } else if(op==3){ cin>>a>>b; rt[i]=rt[i-1]; int fx=find(rt[i],a),fy=find(rt[i],b); if(fx==fy) cout<<1<<'\n'; else cout<<0<<'\n'; } } return 0; }
|