跳到正文

剪贴板

剪贴板 v3swdrs9

原文
剪贴板信息

剪贴板信息

收录
更新

Splay(文艺)

C++
#include<bits/stdc++.h>
#define inf 2147483647
#define int long long
#define tiao cout<<"IAKIOI"<<endl
using namespace std;
int n,q;
int top,rt;
struct fish{
    int fath,v,s[2],cnt,siz,lazy;
}a[1000005];
int shulie[1000005];
void maintain(int x){a[x].siz=a[a[x].s[0]].siz+a[a[x].s[1]].siz+1;}
void clear(int x){a[x].s[0]=a[x].s[1]=a[x].fath=a[x].v=a[x].siz=a[x].cnt=a[x].lazy=0;}
bool get(int x){return x==a[a[x].fath].s[1];}
void rotate(int x){
    int y=a[x].fath;
    int z=a[y].fath;
    int chk=get(x);
    a[y].s[chk]=a[x].s[chk^1];
    if(a[x].s[chk^1])a[a[x].s[chk^1]].fath=y;
    a[x].s[chk^1]=y;
    a[y].fath=x;
    a[x].fath=z;
    if(z)a[z].s[y==a[z].s[1]]=x;
    maintain(y);
    maintain(x);
}
void splay(int x,int g=0){
    if(g==0)rt=x;
    while(a[x].fath!=g){
        int f=a[x].fath,gg=a[a[x].fath].fath;
        if(gg!=g){
            if(get(f)==get(x))rotate(f);
            else rotate(x);
        }
        rotate(x);
    }
}
void tagrev(int x){
    swap(a[x].s[0],a[x].s[1]);
    a[x].lazy^=1;
}
void pushdown(int x){
    if(a[x].lazy){
        tagrev(a[x].s[0]),
        tagrev(a[x].s[1]),
        a[x].lazy=0;
    }
}
int build(int l,int r,int f){
    if(l>r)return 0;
    int mid=(l+r)>>1;
    int cur=++top;
    a[cur].v=shulie[mid],a[cur].fath=f;
    a[cur].s[0]=build(l,mid-1,cur);
    a[cur].s[1]=build(mid+1,r,cur);
    maintain(cur);
    return cur;
}
int rk_to_v(int k){
    int cur=rt;
    while(1){
        pushdown(cur);
        if(a[cur].s[0]&&k<=a[a[cur].s[0]].siz)
        cur=a[cur].s[0];
        else{
            k-=1+a[a[cur].s[0]].siz;
            if(k<=0){
                splay(cur);
                return cur;
            }
            cur=a[cur].s[1];
        }
    }
}
void reverse(int l,int r){
    int L=rk_to_v(l),R=rk_to_v(r+2);
    splay(L),splay(R,L);
    tagrev(a[a[L].s[1]].s[0]);
}
void print(int x){
    pushdown(x);
    if(a[x].s[0])print(a[x].s[0]);
    if(a[x].v>=1&&a[x].v<=n)cout<<a[x].v<<' ';
    if(a[x].s[1])print(a[x].s[1]);
}
signed main(){
    cin>>n>>q;
    for(int i=0;i<=n+1;i++)
    shulie[i]=i;
    rt=build(0,n+1,0);
    while(q--){
        int l,r;
        cin>>l>>r;
        reverse(l,r);
    }
    print(rt);
    return 0;
}

学习资料♂

点此返回喵 ~