# [BZOJ3223]Tyvj 1729 文艺平衡树

5 3

1 3

1 3

1 4

4 3 2 1 5

N,M<=100000

## 代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define maxn (int)(1e5+1000)
#define inf (int)(1e9+1000)
using namespace std;
int
val[maxn],tag[maxn],size[maxn],son[maxn][2],fa[maxn],cnt[maxn],s[maxn];
int n,m,idx,root;
void push_down(int x){
if(!tag[x])return;
if(son[x][0]){
tag[son[x][0]]^=1;
}
if(son[x][1]){
tag[son[x][1]]^=1;
}
tag[x]=0;
swap(son[x][0],son[x][1]);
return;
}
void push_up(int x){
size[x]=cnt[x];
if(son[x][0]){
size[x]+=size[son[x][0]];
}
if(son[x][1]){
size[x]+=size[son[x][1]];
}
return;
}
void Down(int x){
if(!x)return;
Down(fa[x]);
push_down(x);
return;
}
void rotate(int x){
int y=fa[x],z=fa[y],o=(son[y][1]==x);
son[y][o]=son[x][o^1];
fa[son[x][o^1]]=y;

son[x][o^1]=y;
fa[y]=x;

son[z][son[z][1]==y]=x;
fa[x]=z;

push_up(y);
push_up(x);
return;
}
void splay(int x,int v=0){
Down(x);
for(int y;fa[x]!=v&&fa[x];rotate(x)){
y=fa[x];
if(fa[y]==v)continue;
rotate((son[fa[x]][0]==x)^(son[fa[y]][0]==y)?x:y);
}
if(!v)root=x;
}
void insert(int x,int a){
int y=0;
while(x&&val[x]!=a){
y=x;
x=son[x][val[x]<a];
}
if(x){
cnt[x]++;push_up(x);
}
else{
x=++idx;
val[x]=a;
tag[x]=son[x][0]=son[x][1]=0;
cnt[x]=size[x]=1;
son[y][val[y]<a]=x;
fa[x]=y;
}
splay(x);
return;
}
int kth(int x,int a){
push_down(x);
if(size[son[x][0]]>=a){
return kth(son[x][0],a);
}
if(size[son[x][0]]+cnt[x]>=a){
splay(x);
return x;
}
return kth(son[x][1],a-cnt[x]-size[son[x][0]]);
}
void write(int x){
if(!x)return;
push_down(x);
write(son[x][0]);
if(-1e9<=val[x]&&val[x]<=1e9)printf("%d ",val[x]);
write(son[x][1]);
return;
}
int main(){
//	freopen("in","r",stdin);
scanf("%d%d",&n,&m);
insert(root,inf);insert(root,-inf);
for(int i=1;i<=n;i++){insert(root,i);}
for(int i=1;i<=m;i++){
int l,r;scanf("%d%d",&l,&r);
l=kth(root,l+1-1);r=kth(root,r+1+1);
splay(l);splay(r,root);
tag[son[son[root][1]][0]]^=1;
push_down(son[son[root][1]][0]);
}
write(root);
return 0;
}

posted @ 2019-04-27 00:41  GavinZheng  阅读(195)  评论(0编辑  收藏  举报