文艺平衡树

#include<stdio.h>
#define N 100005
int n,m;
int root,fa[N],ch[N][2],size[N],rev[N];
void swap(int &a,int &b) {
    a^=b, b^=a, a^=b;
}
int son(int t) {
    return t==ch[fa[t]][1];
}
void pushup(int t) {
    size[t]=size[ch[t][0]]+size[ch[t][1]]+1;
}
void pushdown(int t) {
    if(rev[t]) {
        swap(ch[t][0],ch[t][1]);
        rev[ch[t][0]]^=1, rev[ch[t][1]]^=1, rev[t]=0;
    }
}
void rotate(int t) {
	pushdown(fa[t]), pushdown(t);
    int p=fa[t], d=son(t);
    ch[p][d]=ch[t][!d];
    if(ch[t][!d]) fa[ch[t][!d]]=p;
    fa[t]=fa[p];
    if(fa[p]) ch[fa[p]][son(p)]=t;
    else root=t;
    fa[p]=t, ch[t][!d]=p;
    pushup(p), pushup(t);
}
void splay(int t,int r) {
    while(fa[t]!=r) {
        int p=fa[t];
        if(fa[p]==r) rotate(t);
        else {
            if(son(t)==son(p)) rotate(p), rotate(t);
            else rotate(t), rotate(t);
        }
    }
}
void build(int l,int r,int p) {
    if(l>r) return;
    int mid=l+r>>1;
    fa[mid]=p, size[mid]=1, ch[p][mid>p]=mid;
    if(l==r) return;
    build(l,mid-1,mid);
    build(mid+1,r,mid);
    pushup(mid);
}
int find(int k) {
    int t=root;
    while(pushdown(t),k!=size[ch[t][0]]+1) {
        if(k<=size[ch[t][0]]) t=ch[t][0];
        else k-=size[ch[t][0]]+1, t=ch[t][1];
    }
    return t;
}
void reverse(int l,int r) {
    l=find(l), r=find(r+2);
    splay(l,0), splay(r,root);
    rev[ch[r][0]]^=1;
}
void dfs(int t) {
    if(!t) return;
    pushdown(t);
    dfs(ch[t][0]);
    if(t!=1&&t!=n+2) printf("%d ",t-1);
    dfs(ch[t][1]);
}
int main() {
    int l,r;
    scanf("%d%d",&n,&m);
    root=n+3>>1;
    build(1,n+2,0), ch[0][1]=0;
    while(m--) {
        scanf("%d%d",&l,&r);
        reverse(l,r);
    }
    dfs(root);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值