[BZOJ3223] 文艺平衡树
传送门
Description
您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 4 1
Input
第一行为n,m n表示初始序列有n个数,这个序列依次是(1,2……n-1,n) m表示翻转操作次数
接下来m行每行两个数[l,r] 数据保证 1<=l<=r<=n
Output
输出一行n个数字,表示原始序列经过m次变换后的结果
Sample Input
5 3
1 3
1 3
1 4
Sample Output
4 3 2 1 5
Solution
- Splay区间翻转模板题
- 保证序列编号满足BST,size[left_son]+1即为根的最终位置
为了弄清上面一条花了一下午- 补一个Splay时间复杂度证明(并不是我写的…)Splay&LCT复杂度证明
强势安利AKteam
Code
/**************************************************************
Problem: 3223
User: df016
Language: C++
Result: Accepted
Time:3024 ms
Memory:3636 kb
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define N 100007
using namespace std;
int rt,n,m,sz;
int size[N],ch[N][2],id[N],lazy[N],fa[N];
void pushup(int k){
size[k]=size[ch[k][0]]+size[ch[k][1]]+1;
}
void pushdown(int k){
if (lazy[k]){
swap(ch[k][0],ch[k][1]);
lazy[ch[k][0]]^=1;
lazy[ch[k][1]]^=1;
lazy[k]=0;
}
}
void rotate(int x,int &k){
int y=fa[x],z=fa[y],l,r;
if (ch[y][0]==x) l=0; else l=1;
r=l^1;
if (y==k) k=x;
else if (ch[z][0]==y) ch[z][0]=x; else ch[z][1]=x;
fa[x]=z; fa[y]=x; fa[ch[x][r]]=y;
ch[y][l]=ch[x][r]; ch[x][r]=y;
pushup(y); pushup(x);
}
void splay(int x,int &k){
while (x!=k){
int y=fa[x],z=fa[y];
if (y!=k)
if ((ch[z][0]==y)^(ch[y][0]==x)) rotate(x,k);
else rotate(y,k);
rotate(x,k);
}
}
int query(int k,int x){
pushdown(k);
int l=ch[k][0],r=ch[k][1];
if (size[l]+1==x) return k;
else if (size[l]>=x) return query(l,x);
else return query(r,x-size[l]-1);
}
void work(int l,int r){
int x=query(rt,l);
int y=query(rt,r+2);
splay(x,rt); splay(y,ch[rt][1]);
lazy[ch[y][0]]^=1;
}
void build(int l,int r,int f){
if (l>r) return;
int now=id[l],last=id[f];
if (l==r){
fa[now]=last; size[now]=1;
if (l<f) ch[last][0]=now;
else ch[last][1]=now;
return;
}
int mid=(l+r)>>1;
now=id[mid];
build(l,mid-1,mid); build(mid+1,r,mid);
fa[now]=last; pushup(mid);
if (mid<f) ch[f][0]=mid;
else ch[f][1]=mid;
}
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=n+2;i++) id[i]=++sz;
build(1,n+2,0); rt=(n+3)>>1;
for (int i=1;i<=m;i++){
int x,y; scanf("%d%d",&x,&y);
work(x,y);
// for (int i=1;i<=n;i++) printf("%d ",query(rt,i+1)-1);
}
for (int i=1;i<=n;i++)
printf("%d ",query(rt,i+1)-1);
return 0;
}