fhq-Treap 文艺平衡树代码记录

#include
#include
#include
#include
#include<string>
using namespace std;
const int N=1e4+10; 
int a[N];
int root;
int idx;
int x,y,z;
struct node{
    int l,r;
    int size;
    int val;
    int key;
    int lazy;
}tr[N];
int get(int key){
    tr[++idx].key=key;
    tr[idx].size=1;
    tr[idx].val=rand();
    return idx;
}
void pushdown(int u){
    if(tr[u].lazy){
        swap(tr[u].l,tr[u].r);
        tr[tr[u].l].lazy^=1;
        tr[tr[u].r].lazy^=1;
        tr[u].lazy=0;
    }
}
void pushup(int u){
    tr[u].size=tr[tr[u].l].size+tr[tr[u].r].size+1;
} 
void spilt(int p,int siz,int &x,int &y){
    if(!p)
    x=y=0;
    else{
        pushdown(p);
        if(tr[tr[p].l].size<siz){
            x=p;
            spilt(tr[p].r,siz-tr[tr[p].l].size-1,tr[p].r,y);
        }
        else{
            y=p;
            spilt(tr[p].l,siz,x,tr[p].l);
        }
        pushup(p);
    }
}
int merge(int x,int y){
    if(!x||!y)
    return x+y;
    if(tr[x].val>=tr[y].val){
        pushdown(x);
        tr[x].r=merge(tr[x].r,y);
        pushup(x);
        return x;
    }
    else{
        pushdown(y);
        tr[y].l=merge(x,tr[y].l);
        pushup(y);
        return y;
    }
}
void reverse(int l,int r){
    spilt(root,l-1,x,y);
    spilt(y,r-l+1,y,z);
    tr[y].lazy^=1;
    root=merge(merge(x,y),z);
}
void vis(int p){
    if(!p)
    return ;
    pushdown(p);
    vis(tr[p].l);
    cout<" ";
    vis(tr[p].r);
}
int main(){
    int i;
    int n;
    int m;
    cin>>n>>m;
    for(i=1;i<=n;i++)
    root=merge(root,get(i));
    while(m--){
        int l,r;
        scanf("%d%d",&l,&r);
        reverse(l,r);
    }
    vis(root);
    return 0;
} 
View Code

 

你可能感兴趣的:(fhq-Treap 文艺平衡树代码记录)