bzoj 3223/tyvj 1729 文艺平衡树 splay tree

时间:2023-03-08 22:39:44

原题链接:http://www.tyvj.cn/p/1729

这道题以前用c语言写的splay tree水过了。。

现在接触了c++重写一遍。。。

只涉及区间翻转,由于没有删除操作故不带垃圾回收,具体如下:

 #include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
const int MAX_N = ;
struct Node{
int v, s, rev;
Node *pre, *ch[];
inline void set(int _v = , int _s = , Node *p = NULL){
v = _v, s = _s, rev = ;
pre = ch[] = ch[] = p;
}
inline void push_up(){
s = ch[]->s + ch[]->s + ;
}
inline void update(){
Node *t = ch[];
rev ^= ;
t = ch[];
ch[] = ch[];
ch[] = t;
}
inline void push_down(){
if (rev != ){
rev ^= ;
ch[]->update();
ch[]->update();
}
}
};
struct SplayTree{
Node stack[MAX_N];
Node *tail, *root, *null;
inline Node *newNode(int v){
Node *p = tail++;
p->set(v, , null);
return p;
}
void initialize(int l, int r){
tail = &stack[];
null = tail++;
null->set(-);
root = newNode(-);
root->ch[] = newNode(-);
root->ch[]->pre = root;
Node *x = built(l, r);
root->ch[]->ch[] = x;
x->pre = root->ch[];
root->ch[]->push_up();
root->push_up();
}
inline void rotate(Node *x, int c){
Node *y = x->pre;
y->push_down(), x->push_down();
y->ch[!c] = x->ch[c];
x->pre = y->pre;
if (x->ch[c] != null) x->ch[c]->pre = y;
if (y->pre != null) y->pre->ch[y->pre->ch[] != y] = x;
x->ch[c] = y;
y->pre = x;
y->push_up();
if (y == root) root = x;
}
void splay(Node *x, Node *f){
if (x == root) return;
for (; x->pre != f; x->push_down()){
if (x->pre->pre == f){
rotate(x, x->pre->ch[] == x);
} else {
Node *y = x->pre, *z = y->pre;
if (z->ch[] == y){
if (y->ch[] == x)
rotate(y, ), rotate(x, );
else rotate(x, ), rotate(x, );
} else {
if (y->ch[] == x)
rotate(y, ), rotate(x, );
else rotate(x, ), rotate(x, );
}
}
}
x->push_up();
}
Node *built(int l, int r){
Node *p = null;
if (l > r) return null;
int mid = (l + r) >> ;
p = newNode(mid);
p->ch[] = built(l, mid - );
if (p->ch[] != null) p->ch[]->pre = p;
p->ch[] = built(mid + , r);
if (p->ch[] != null) p->ch[]->pre = p;
p->push_up();
return p;
}
Node *select(Node *x, int k){
int t = ;
Node *ret = x;
for (;;){
ret->push_down();
t = ret->ch[]->s;
if (t == k) break;
if (k < t) ret = ret->ch[];
else k -= t + , ret = ret->ch[];
}
return ret;
}
void travel(Node *x){
if (x != null){
x->push_down();
travel(x->ch[]);
printf("%d ", x->v);
travel(x->ch[]);
}
}
Node *get_range(int l, int r){
splay(select(root, l - ), null);
splay(select(root, r + ), root);
return root->ch[]->ch[];
}
void reverse(int l, int r){
Node *ret = get_range(l, r);
ret->update();
}
void print(int n){
Node *ret = get_range(, n);
travel(ret);
}
}Splay;
int main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int n, m, a, b;
while (~scanf("%d %d", &n, &m)){
Splay.initialize(, n);
while (m--){
scanf("%d %d", &a, &b);
Splay.reverse(a, b);
}
Splay.print(n);
}
return ;
}