洞穴勘测(LCT)

题意:有n个点,有m个操作

操作:

Connect u v :把u和v连起来

Destroy u v:把u和v的边删除

Query u v:询问u和v是否联通

询问时可以用真实树中的树根是否一致来判断

参考代码:

#include<stdio.h>
#include<algorithm>
#define N 200005
using namespace std;

int rev[N],sz[N],ch[N][2],pre[N],st[N],t,n,val[N];

bool is_root(int x){return !pre[x]||(ch[pre[x]][0]!=x&&ch[pre[x]][1]!=x);}

bool side(int x){return ch[pre[x]][1]==x;}

void push_rev(int x)
{
    if(!rev[x])return;
    rev[x]=0;swap(ch[x][0],ch[x][1]);
    if(ch[x][0])rev[ch[x][0]]^=1;
    if(ch[x][1])rev[ch[x][1]]^=1;
}

void update(int x)
{
    sz[x]=1;
    if(ch[x][0])sz[x]+=sz[ch[x][0]];
    if(ch[x][1])sz[x]+=sz[ch[x][1]];
}

void rotate(int x)
{
    int y=pre[x],z=pre[y];
    bool f=ch[y][1]==x;
    if(!is_root(y))ch[z][ch[z][1]==y]=x;
    ch[y][f]=ch[x][!f];ch[x][!f]=y;
    pre[x]=z;pre[y]=x;pre[ch[y][f]]=y;
    update(y);update(x);
}

void splay(int x)
{
    st[t=1]=x;
    for(int y=x;!is_root(y);st[++t]=y=pre[y]);
    for(;t;t--)if(rev[st[t]])push_rev(st[t]);
    while(!is_root(x))
    {
        if(!is_root(pre[x]))
        {
            if(side(x)==side(pre[x]))rotate(pre[x]);
            else rotate(x);
        }
        rotate(x);
    }
    update(x);
}

void access(int x)
{
    for(int t=0;x;ch[x][1]=t,t=x,x=pre[x])splay(x);
}

void make_root(int x)
{
    access(x);
    splay(x);
    rev[x]^=1;
}

void link(int x,int y)
{
    make_root(x);
    pre[x]=y;
}

int findroot(int x)
{
    access(x);
    splay(x);
    push_rev(x);
    while(ch[x][0])push_rev(x),x=ch[x][0];
    splay(x);
    return x;
}

void cut(int x,int y)
{
    make_root(x);
    if(findroot(y)==x&&pre[y]==x&&!ch[y][0])
    {
        pre[y]=ch[x][1]=0;
        update(x);
    }
}

void path(int x,int y)
{
    make_root(x);
    access(y);
    splay(y);
}

int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    char op[10];
    int x,y;
    for(int i=1;i<=m;i++)
    {
        scanf("%s%d%d",op,&x,&y);
        if(op[0]=='Q')
        {
            if(findroot(y)==findroot(x))printf("Yes\n");
            else printf("No\n");
        }
        else if(op[0]=='D')
        {
            cut(x,y);
        }
        else
        {
            link(x,y);
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值