Dynamic Tree Connectivity(LCT)

文章目录

题目

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");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值