BZOJ 2049 [Sdoi2008]Cave 洞穴勘测

LCT模板题

顺便挂一个不错的LCT教程:link-cut trees

#include<cstdio>
#include<algorithm>
#define N 10005
using namespace std;
struct node
{
    int fa, ch[2], lazy; 
}t[N];
char s[10];
int stk[N], top;
void pushdown(int x)
{
    if(t[x].lazy)
    {
        t[x].lazy=0;
        swap(t[x].ch[0],t[x].ch[1]);
        t[t[x].ch[0]].lazy^=1;
        t[t[x].ch[1]].lazy^=1;
    }
}
bool isroot(int x)
{
    return t[t[x].fa].ch[0]!=x && t[t[x].fa].ch[1]!=x;
}
void rot(int x)
{
    int fa=t[x].fa;
    int gfa=t[fa].fa;
    int t1=(t[fa].ch[0]!=x);
    int t2=(t[gfa].ch[0]!=fa);
    int ch=t[x].ch[t1^1];
    if(!isroot(fa))t[gfa].ch[t2]=x;
    t[ch].fa=fa;
    t[x].fa=gfa;
    t[x].ch[1^t1]=fa;
    t[fa].fa=x;
    t[fa].ch[t1]=ch;    
}
void splay(int x)
{
    stk[++top]=x;
    for(int i = x; !isroot(i); i=t[i].fa)
        stk[++top]=t[i].fa;
    while(top)
        pushdown(stk[top--]);
    while(!isroot(x))
    {
        int fa=t[x].fa;
        int gfa=t[fa].fa;
        if(!isroot(fa))
            (t[fa].ch[0]==x)^(t[gfa].ch[0]==fa)?rot(x):rot(fa);
        rot(x);
    }
}
void access(int x)
{
    int temp=0;
    while(x)
    {
        splay(x);
        t[x].ch[1]=temp;
        temp=x;
        x=t[x].fa;
    }
}
void makeroot(int x)
{
    access(x);
    splay(x);
    t[x].lazy^=1;
}
int findroot(int x)
{
    access(x);
    splay(x);
    int temp=x;
    while(t[temp].ch[0])
        temp=t[temp].ch[0];
    return temp;
}
void link(int x, int y)
{
    makeroot(x);
    t[x].fa=y;
}
void cut(int x, int y)
{
    makeroot(x);
    access(y);
    splay(y);//这里需要进行一次旋转,因为access前x和y是否属于同一个SplayTree会使x和y的相对位置不同 
    t[x].fa=t[y].ch[0]=0;
}
int main()
{
    int n, m;
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= m; i++)
    {
        int a, b;
        scanf("%s%d%d",s,&a,&b);
        if(s[0]=='Q')
        {
            if(findroot(a)==findroot(b))
                printf("Yes\n");
            else printf("No\n");
        }
        else if(s[0]=='C')
            link(a,b);
        else 
            cut(a,b);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值