#include<bits/stdc++.h>
using namespace std;
struct Node{
Node *ch[2],*fa;
int key,siz;
bool flip;
Node(int);
int dir(int val){
if(val==ch[0]->siz+1) return -1;
return val>ch[0]->siz+1;
}
int son(){
if(fa->ch[0]==this) return 0;
if(fa->ch[1]==this) return 1;
return -1;
}
void maintain(){siz=ch[0]->siz+ch[1]->siz+1;}
void pushdown(){
if(flip){
swap(ch[0],ch[1]);
ch[0]->flip^=1;ch[1]->flip^=1;
flip=false;
}
}
}*null,*root;
Node::Node(int _=-1){
key=_;
siz=null?1:0;
flip=false;
ch[0]=ch[1]=fa=null;
}
void buildtree(Node* &o,int l,int r){
if(l>r) {o=null;return;}
int mid=l+r>>1;
o=new Node(mid);
buildtree(o->ch[0],l,mid-1);o->ch[0]->fa=o;
buildtree(o->ch[1],mid+1,r);o->ch[1]->fa=o;
o->maintain();
}
void Rotate(Node *o,int dir){
Node *tmp=o->ch[dir^1];
o->ch[dir^1]=tmp->ch[dir];
tmp->ch[dir]->fa=o;
tmp->ch[dir]=o;
o->maintain(); tmp->maintain();
if(~o->son()) o->fa->ch[o->son()]=tmp;
tmp->fa=o->fa; o->fa=tmp;
}
void print(Node *o){
if(o==null) return;
o->pushdown();
print(o->ch[0]);
printf("%d ",o->key);
print(o->ch[1]);
}
void Pushdown(Node *o){
if(o->fa!=null) Pushdown(o->fa);
o->pushdown();
}
void Splay(Node *o){
while(~o->son()){
int dir=o->son();
if(dir==o->fa->son()) Rotate(o->fa->fa,dir^1);
Rotate(o->fa,dir^1);
}
}
Node *Kth(Node *o,int k){
o->pushdown();
int dir=o->dir(k);
if(dir==1) k-=o->ch[0]->siz+1;
if(dir==-1) return o;
else return Kth(o->ch[dir],k);
}
Node *Merge(Node *lhs,Node *rhs){
if(lhs==null) return rhs;
if(rhs==null) return lhs;
Node *tmp=Kth(lhs,lhs->siz);
Splay(tmp);
tmp->ch[1]=rhs;
rhs->fa=tmp;
tmp->maintain();
return tmp;
}
void Split(Node *org,int k,Node* &lhs,Node* &rhs){
if(k==0){
lhs=null;rhs=org;
return;
}
else if(k==org->siz){
lhs=org;rhs=null;
return;
}
Node* tmp=Kth(org,k);
Splay(tmp);
lhs=tmp;rhs=tmp->ch[1];
rhs->fa=null;lhs->ch[1]=null;lhs->maintain();
}
void Reverse(int l,int r){
Node *lhs,*tmp,*mid,*rhs;
Split(root,l-1,lhs,mid);
Split(mid,r-l+1,mid,rhs);
mid->flip^=1;
root=Merge(Merge(lhs,mid),rhs);
}
int main(){
null=new Node();
null->ch[0]=null->ch[1]=null->fa=null;
root=null;
int n,m;
scanf("%d%d",&n,&m);
buildtree(root,1,n);
for(int i=1;i<=m;++i){
int l,r;
scanf("%d%d",&l,&r);
Reverse(l,r);
}
print(root);
return 0;
}
splay模板
最新推荐文章于 2021-02-09 21:03:02 发布