题目:文艺平衡树
如果不懂基础知识可以看本蒟蒻写的
treap小结
本题是动态的序列翻转
首先我们知道splay是可以分裂和合并的
我们可以打一个lazy标记,表示这棵子树有没有翻转过
一开始不知道如何建树
想过Insert
但是效率低并且有点不像splay
所以就来了一个Build
要注意先序遍历
后来调试发现rotate写反了(捂脸)
注意Splay中的
Node* w=o->ch[d];
if(d==e)Rotate(o,d^1);
else Rotate(o->ch[d],e^1);
不能写成
Node* w=o->ch[d];
if(d==e)Rotate(o,d^1);
else Rotate(w,e^1);
因为这里是一段引用
rotate中二段旋转不能写错,否则效率降低
Print时要pushdown
分裂时先把p-1旋转到根节点
然后取右子树
然后把q旋转到根节点
取左子树就是【p,q】了
有一个一个虚拟节点0
保证split不出错
完整ac代码
#include<cstdio>
#include<iostream>
#define N 100010
using namespace std;
int n,num,p,q,m;
struct Node{
Node* ch[2];
int v,s,f;
int cmp(int x){
if(ch[0]->s+1==x)return -1;
return ch[0]->s+1 < x;
}
void maintain(){
s=ch[0]->s+ch[1]->s+1;
}
void pushdown(){
if(f){
f=0;
swap(ch[0],ch[1]);
ch[0]->f=!ch[0]->f;
ch[1]->f=!ch[1]->f;
}
}
};
Node* null=new Node();
Node *ro,*l,*r,*mid,*o;
void Build(Node* &o,int sz){
if(!sz){
o=null;
return ;
}
o=new Node();
Build(o->ch[0],sz/2);
o->v=num++;
Build(o->ch[1],sz-sz/2-1);
o->maintain();
}
void Rotate(Node* &o,int d){
Node* k=o->ch[d^1]; o->ch[d^1]=k->ch[d]; k->ch[d]=o;
o->maintain(); k->maintain(); o=k;
}
void Splay(Node* &o,int k){
o->pushdown();
int d=o->cmp(k);
if(d==1)k-=o->ch[0]->s+1;
if(d!=-1){
Node* w=o->ch[d];
w->pushdown();
int e= w->cmp(k);
if(e==1) k-= w->ch[0]->s+1;
if(e!=-1){
Splay(w->ch[e],k);
if(d==e)Rotate(o,d^1);
else Rotate(o->ch[d],e^1);
}
Rotate(o,d^1);
}
}
Node* Merge(Node* l,Node* r){
Splay(l,l->s);
l->ch[1]=r;
l->maintain();
return l;
}
void Split(Node* &o,int k,Node* &l,Node* &r){
Splay(o,k);
l=o;
r=o->ch[1];
o->ch[1]=null;
l->maintain();
}
void Print(Node* o){
if(o!=null){
o->pushdown();
Print(o->ch[0]);
if(o->v!=0)printf("%d ",o->v);
Print(o->ch[1]);
}
}
int main(){
freopen("data.txt","r",stdin);
scanf("%d%d",&n,&m);
Build(ro,n+1);
for(int i=1;i<=m;i++){
scanf("%d%d",&p,&q);
Split(ro,p,l,o);
Split(o,q-p+1,mid,r);
mid->f^=1;
ro=Merge(l,Merge(mid,r));
// Print(ro);
// printf("\n");
}
Print(ro);
}