#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);
}
文艺平衡树
最新推荐文章于 2021-02-17 16:30:42 发布