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 102 103 104 105 106
| #include<bits/stdc++.h> using namespace std; template<typename tpos> void scan(tpos &x) { tpos f=1;x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} x*=f; } template<typename tpos,typename... Tpos> void scan(tpos &x,Tpos &...X) { scan(x),scan(X...); } template<typename tpop> void print(tpop x) { if(x<0)putchar('-'),x=-x; if(x>9)print(x/10); putchar(x%10+'0'); } template<typename tpop,typename... Tpop> void print(tpop x,Tpop ...X) { print(x),putchar(' '),print(X...); } int n,q,tot=0,rt[200005],a[200005];
int son[200000*20][2],fa[200000*20],level[200000*20];
void build(int &rt,int l,int r) { rt=++tot; int mid=(l+r)>>1; if(l==r) { fa[rt]=l; return; } build(son[rt][0],l,mid); build(son[rt][1],mid+1,r); } void newpoint(int &rt,int old,int l,int r,int x,int father) { rt=++tot; int mid=(l+r)>>1; if(l==r) { fa[rt]=father; level[rt]=level[old]; return; } son[rt][0]=son[old][0]; son[rt][1]=son[old][1]; if(x<=mid)newpoint(son[rt][0],son[old][0],l,mid,x,father); else newpoint(son[rt][1],son[old][1],mid+1,r,x,father); } void addlevel(int rt,int l,int r,int x) { int mid=(l+r)>>1; if(l==r) { ++level[rt]; return; } if(x<=mid)addlevel(son[rt][0],l,mid,x); else addlevel(son[rt][1],mid+1,r,x); } int query(int rt,int l,int r,int x) { int mid=(l+r)>>1; if(l==r)return rt; if(x<=mid)return query(son[rt][0],l,mid,x); else return query(son[rt][1],mid+1,r,x); } int getfa(int rt,int x) { int father=query(rt,1,n,x); return fa[father]==x?father:getfa(rt,fa[father]); } void connect(int v,int x,int y) { int fx=getfa(rt[v],x),fy=getfa(rt[v],y); if(fx==fy)return; if(level[fx]<level[fy])swap(fx,fy); newpoint(rt[v],rt[v-1],1,n,fa[fy],fa[fx]); if(level[fx]==level[fy]) addlevel(rt[v],1,n,fa[fx]); } int main() { scan(n,q); build(rt[0],1,n); for(int i=1,op,x,y;i<=q;i++) { scan(op); switch(op) { case 1:scan(x,y);rt[i]=rt[i-1];connect(i,x,y);break; case 2:scan(x);rt[i]=rt[x];break; case 3:scan(x,y);rt[i]=rt[i-1];print(getfa(rt[i],x)==getfa(rt[i],y)),putchar('\n');break; } } return 0; }
|