洞穴勘察

#include<iostream>
#include<string>
#include<cstdio>
#define N 200005
using namespace std;

inline int read() {
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int n,m;
bool rev[N];
int next[N],c[N][2];
int fa[N],size[N],st[N];

inline bool isroot(int k){
    return c[fa[k]][0]!=k&&c[fa[k]][1]!=k;
}
inline void pushup(int x){
    size[x]=size[c[x][0]]+size[c[x][1]]+1;
}
void pushdown(int k){
    int l=c[k][0],r=c[k][1];
    if(rev[k]){
        rev[k]^=1;rev[l]^=1;rev[r]^=1;
        swap(c[k][0],c[k][1]);
    }
}
void rotate(int x){
    int y=fa[x],z=fa[y],l,r;
    if(c[y][0]==x)l=0;else l=1;r=l^1;
    if(!isroot(y))
        if(c[z][0]==y)c[z][0]=x;else c[z][1]=x;
    fa[x]=z;fa[y]=x;fa[c[x][r]]=y;
    c[y][l]=c[x][r];c[x][r]=y;
    pushup(y);pushup(x);
}
void splay(int x){
    int top=0;st[++top]=x;
    for(int i=x;!isroot(i);i=fa[i])
        st[++top]=fa[i];
    for(int i=top;i;i--)pushdown(st[i]);
    while(!isroot(x)){
        int y=fa[x],z=fa[y];
        if(!isroot(y))
            if(c[y][0]==x^c[z][0]==y)rotate(x);
            else rotate(y);
        rotate(x);
    }
}
void access(int x){
    int t=0;
    while(x){
        splay(x);
        c[x][1]=t;
        t=x;x=fa[x];
    }
}
void beroot(int x){
    access(x);splay(x);rev[x]^=1;
}
void merge(int x,int y){
    beroot(x);fa[x]=y;splay(x);
}
void split(int x,int y){
    beroot(x);access(y);splay(y);c[y][0]=fa[x]=0;
}
int main(){
    n=read();
    m=read();
    string s1;
    int s2,s3;
    for(int i=1;i<=m;++i){
        cin>>s1;
        s2=read();s3=read()
        if(s1[0]=='Q'){
            if(find(s2)==find(s3))
                cout<<"Yes\n";
            else cout<<"No\n";
        }
        else if(s1[0]=='C')
            merge(s2,s3);
        else split(s2,s3);
    }
    return 0;
}
posted @ 2017-12-30 19:14  Grary  阅读(182)  评论(0编辑  收藏  举报
博客园 首页 私信博主 编辑 关注 管理 新世界