[BZOJ2049][SDOI2008]Cave 洞穴勘测(LCT)

211 篇文章 0 订阅
17 篇文章 0 订阅

题目描述

传送门

题解

Link-Cut-Tree模板题。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

const int max_n=2e6+5;

int n,m,x,y;
int f[max_n],ch[max_n][2],size[max_n],reverse[max_n];
int strack[max_n];
char s[10];

inline int get(int x){
    return ch[ f[x] ][1]==x;
}

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

inline void pushdown(int x){
    if (x&&reverse[x]){
        swap(ch[x][0],ch[x][1]);
        if (ch[x][0]) reverse[ ch[x][0] ]^=1;
        if (ch[x][1]) reverse[ ch[x][1] ]^=1;
        reverse[x]=0;
    }
}

inline int Is_Root(int x){
    return ch[ f[x] ][0]!=x&&ch[ f[x] ][1]!=x;
}

inline void rotate(int x){
    int old=f[x],oldf=f[old],which=get(x);

    if (!Is_Root(old))
      ch[oldf][ ch[oldf][1]==old ]=x;
    f[x]=oldf;

    ch[old][which]=ch[x][which^1];
    f[ ch[old][which] ]=old;

    ch[x][which^1]=old;
    f[old]=x;

    update(old);
    update(x);
}

inline void splay(int x){
    int top=0;
    strack[++top]=x;
    for (int i=x; !Is_Root(i); i=f[i])
      strack[++top]=f[i];
    for (int i=top; i>=1; --i) pushdown( strack[i] );  

    for (int fa; !Is_Root(x); rotate(x))
      if (!Is_Root(fa=f[x]))
        rotate( (get(x)==get(fa)) ?fa:x);
}

inline void Access(int x){
    int t=0;
    for (; x; t=x,x=f[x]){
        splay(x);
        ch[x][1]=t;
    }
}

inline void Reverse(int x){
    Access(x);
    splay(x);
    reverse[x]^=1;
}

inline int find(int x){
    Access(x);
    splay(x);
    while (ch[x][0])
      x=ch[x][0];
    return x;
}

inline void Link(int x,int y){
    Reverse(x);
    f[x]=y;
    splay(x);
}

inline void Cut(int x,int y){
    Reverse(x);
    Access(y);
    splay(y);
    ch[y][0]=f[x]=0;
}

int main(){
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;++i){
        scanf("%s",s);
        scanf("%d%d",&x,&y);
        if (s[0]=='Q'){
            if (find(x)==find(y)) 
              printf("Yes\n");
            else
              printf("No\n");
        }
        if (s[0]=='C')
          Link(x,y);
        if (s[0]=='D')
          Cut(x,y);
    }
}

总结

花了挺长的时间学了LCT,还不是很熟练,还要继续写一些题来熟练。
给初学者的建议:
1、首先先学会链剖和splay,并能掌握它们的原理,熟练写模板。
2、了解LCT和链剖定义的不同,明确Access/Reverse操作各自的作用和原理。
3、在理解操作的原理之后,研究Link/Cut/Find操作如何将它们结合起来。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值