【模板】文艺平衡树(Splay)

题目链接:传送门
题解:
维护区间翻转
按照数组下标建splay,每次翻转先将l-1移到根,再将r+1移到根的右子树,那么r+1左子树就是要操作的区间,打个flag就好

//by sdfzchy
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int inf=(1<<30),N=100010;
int n,m,cnt,root;
#define pa t[x].fa
#define ls t[x].ch[0]
#define rs t[x].ch[1]
inline int in()
{
    char ch=getchar();
    int f=1,tmp=0;
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') {tmp=(tmp<<1)+(tmp<<3)+(ch-'0');ch=getchar();}
    return tmp*f;
}

struct node
{
    int ch[2],fa,cnt,siz,col;
}t[N];
inline void upd(int x) {t[x].siz=t[ls].siz+t[rs].siz+t[x].cnt;}
int build(int l,int r)
{
    if(l>r) return 0;
    int x=(l+r)>>1;
    ls=build(l,x-1),rs=build(x+1,r);
    t[ls].fa=t[rs].fa=x;
    t[x].cnt=1;t[x].col=0;
    upd(x);
    return x;
}
inline int gi(int x) {return t[pa].ch[1]==x;}
inline void pushdown(int x)
{
    if(!t[x].col) return;
    swap(ls,rs);
    t[ls].col^=1;
    t[rs].col^=1;
    t[x].col=0;
}
void rot(int x)
{
    int f=pa,g=t[f].fa,o=gi(x);
    t[f].ch[o]=t[x].ch[!o];
    t[t[x].ch[!o]].fa=f;
    t[x].ch[!o]=f;
    t[f].fa=x;
    t[x].fa=g;
    if(g) t[g].ch[t[g].ch[1]==f]=x;
    upd(f);upd(x);
}

void splay(int x,int tar)
{
    for(;t[x].fa!=tar;rot(x))
        if(t[pa].fa!=tar)
            rot((gi(x)==gi(pa))?pa:x);
    if(!tar) root=x;        
}

int kth(int k)
{
    int x=root;
    while(1)
    {
        pushdown(x);
        if(k<=t[ls].siz&&ls) x=ls;
        else
        {
            int tmp=t[ls].siz+t[x].cnt;
            if(k<=tmp) return x;
            k-=tmp;x=rs;
        }
    }
}

void print(int x)
{
    if(!x) return;
    pushdown(x);
    if(ls) print(ls);
    if(x!=1&&x!=n+2) printf("%d ",x-1);
    if(rs) print(rs);

}

int main()
{
    n=in(),m=in();
    root=build(1,n+2);
    for(int i=1,l,r;i<=m;i++)
    {
        l=in(),r=in();
        splay(kth(l),0);
        int x=kth(r+2);
        splay(x,root);
        t[ls].col^=1;
    }
    print(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值