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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<time.h> #include<stdio.h> #include<stdlib.h> #include<algorithm> using namespace std; const int Array_Limit=200005; int N,M,a[Array_Limit<<5],root[Array_Limit<<5],ch[Array_Limit<<5][2],nodenum; struct node{ int fa,dep; }; node record[Array_Limit<<5]; void build(int l,int r,int p){ if(l==r){ record[p].fa=a[l]; record[p].dep=1; return; } int mid=(l+r)>>1; build(l,mid,ch[p][0]=++nodenum); build(mid+1,r,ch[p][1]=++nodenum); record[p].fa=max(record[ch[p][0]].fa,record[ch[p][1]].fa); record[p].dep=max(record[ch[p][0]].dep,record[ch[p][1]].dep); } void change(int l,int r,int from,int to,int k,node data){ if(l==r){ record[to].fa=data.fa; record[to].dep=max(record[to].dep,1); return; } int mid=(l+r)>>1; if(k<=mid){ ch[to][0]=++nodenum; ch[to][1]=ch[from][1]; change(l,mid,ch[from][0],ch[to][0],k,data); } else{ ch[to][1]=++nodenum; ch[to][0]=ch[from][0]; change(mid+1,r,ch[from][1],ch[to][1],k,data); } record[to].fa=max(record[ch[to][0]].fa,record[ch[to][1]].fa); record[to].dep=max(record[ch[to][0]].dep,record[ch[to][1]].dep); } node find(int l,int r,int v,int k){ if(l==r) return record[v]; int mid=(l+r)>>1; if(k<=mid) return find(l,mid,ch[v][0],k); else return find(mid+1,r,ch[v][1],k); } void print(int p){ if(p==0) return; printf("%d:%d(",p,record[p].fa); print(ch[p][0]); printf(","); print(ch[p][1]); printf(")"); } int main(){ srand(time(NULL)); scanf("%d%d",&N,&M); for(int i=1;i<=N;i++) a[i]=i; build(1,N,root[0]=++nodenum); node a,b; for(int i=1,op;i<=M;i++){ scanf("%d",&op); if(op==1){ scanf("%d%d",&a.fa,&b.fa); while(a.fa!=find(1,N,root[i-1],a.fa).fa) a=find(1,N,root[i-1],a.fa); while(b.fa!=find(1,N,root[i-1],b.fa).fa) b=find(1,N,root[i-1],b.fa); if(a.dep<b.dep){ a.dep=max(a.dep-1,b.dep)+1; change(1,N,root[i-1],root[i]=++nodenum,b.fa,a); } else{ b.dep=max(a.dep,b.dep-1)+1; change(1,N,root[i-1],root[i]=++nodenum,a.fa,b); } } else if(op==2){ int a; scanf("%d",&a); root[i]=root[a]; } else{ scanf("%d%d",&a.fa,&b.fa); root[i]=root[i-1]; while(a.fa!=find(1,N,root[i],a.fa).fa) a=find(1,N,root[i],a.fa); while(b.fa!=find(1,N,root[i],b.fa).fa) b=find(1,N,root[i],b.fa); printf("%d\n",(a.fa==b.fa)?1:0); } } return 0; }
|