【模板】文藝平衡樹(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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章