Dynamic Tree Connectivity(LCT)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/C20190102/article/details/102510452

文章目录

题目

Dynamic Tree Connectivity

分析

动态树(LCT)初探

题目

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

int read(){
    int x=0;bool f=0;char c=getchar();
    while(c<'0'||c>'9') f|=c=='-',c=getchar();
    while(c>='0'&&c<='9') x=x*10+(c^48),c=getchar();
    return f?-x:x;
}

#define IL inline
#define LL long long
#define MAXN 100000
#define INF 0x7fffffff

struct Node{
    bool rev;
    Node *fa,*ch[2];
}*NIL,Sp[MAXN+5];

IL bool Dir(Node *u){
    return u->fa->ch[1]==u;
}
IL bool isRoot(Node *u){
    return u->fa==NIL||(u->fa->ch[0]!=u&&u->fa->ch[1]!=u);
}
IL void SetChild(Node *u,Node *v,bool d){
    u->ch[d]=v;
    if(v!=NIL)
        v->fa=u;
}
IL void PushDown(Node *u){
    if(u->rev){
        u->rev=0;
        swap(u->ch[0],u->ch[1]);
        u->ch[0]->rev^=1;
        u->ch[1]->rev^=1;
    }
}

IL void Rotate(Node *u){
    bool d=Dir(u);
    Node *y=u->fa;
    if(isRoot(y))
        u->fa=y->fa;
    else
        SetChild(y->fa,u,Dir(y));
    SetChild(y,u->ch[!d],d);
    SetChild(u,y,!d);
}
void Go(Node *u){
    if(!isRoot(u))
        Go(u->fa);
    PushDown(u);
}
void Splay(Node *u){
    Go(u);
    while(!isRoot(u)){
        Node *y=u->fa;
        if(isRoot(y))
            Rotate(u);
        else{
            if(Dir(u)==Dir(y))
                Rotate(y);
            else
                Rotate(u);
            Rotate(u);
        }
    }
}
Node *Access(Node *u){
    Node *r=NIL;
    while(u!=NIL){
        Splay(u);
        SetChild(u,r,1);
        r=u,u=u->fa;
    }
    return r;
}
Node *GetRoot(Node *u){
    Access(u);
    Splay(u);
    Node *r=u;
    while(r->ch[0]!=NIL)
        r=r->ch[0];
    Splay(r);
    return r;
}
IL void MakeRoot(Node *u){
    Access(u);
    Splay(u);
    u->rev^=1;
}
IL void Link(Node *u,Node *v){
    MakeRoot(u);
    u->fa=v;
}
IL void Cut(Node *u,Node *v){
    MakeRoot(u);
    Access(v);
    Splay(v);
    u->fa=NIL;
    v->ch[0]=NIL;
}

int main(){
    int N=read(),M=read();
    NIL=&Sp[0];
    NIL->fa=NIL->ch[0]=NIL->ch[1]=NIL;
    for(int i=1;i<=N;i++)
        Sp[i]=*NIL;
    while(M--){
        char opt[10];
        scanf("%s",opt);
        Node *u=&Sp[read()],*v=&Sp[read()];
        if(opt[0]=='a')
            Link(u,v);
        else if(opt[0]=='r')
            Cut(u,v);
        else
            puts(GetRoot(u)==GetRoot(v)?"YES":"NO");
    }
}

猜你喜欢

转载自blog.csdn.net/C20190102/article/details/102510452