神级数据结构
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 200 + 7;
int m, n;
struct node {
node *left, *right;
node *par;
int val, w;
} *root;
void RightRotate(node *x) {
node *y = x->par;
y->left = x->right;
if(x->right) x->right->par = y;
x->par = y->par;
if(y->par) {
if(y->par->left == y) y->par->left = x;
else y->par->right = x;
}
x->right = y;
y->par = x;
}
void LeftRotate(node *x) {
node *y = x->par;
y->right = x->left;
if(x->left) x->left->par = y;
x->par = y->par;
if(y->par) {
if(y->par->left == y) y->par->left = x;
else y->par->right = x;
}
x->left = y;
y->par = x;
}
void splay(node *x, node *y) {
while(x->par != y) {
if(x->par->par == y) x->par->left == x ? RightRotate(x) : LeftRotate(x);
else {
if(x->par->par->left == x->par) {
if(x->par->left == x) {
RightRotate(x);
RightRotate(x);
} else {
LeftRotate(x);
RightRotate(x);
}
} else {
if(x->par->left == x) {
RightRotate(x);
LeftRotate(x);
} else {
LeftRotate(x);
LeftRotate(x);
}
}
}
}
if(y == 0) root = x;
}
void Insert(int val) {
node *p = root, *y = NULL;
int isL = 1;
while(true) {
if(!p) {
p = new node;
p->left = p->right = NULL;
p->val = val;
p->w = 1;
p->par = y;
if(y) {
if(isL) y->left = p;
else y->right = p;
}
splay(p, 0);
break;
}
y = p;
if(p->val == val) {
p->w++;
splay(p, 0);
break;
} else if(p->val < val) {
p = p->right;
isL = 0;
} else {
p = p->left;
isL = 1;
}
}
}
node *join(node *a, node *b) {
if(!a) return b;
if(!b) return a;
a->par = b->par = 0;
node *t = a;
while(t->right) t = t->right;
splay(t, 0);
t->right = b;
b->par = t;
return t;
}
void Remove(node *x, int val) {
if(x->val == val) {
splay(x, 0);
root = join(x->left, x->right);
return ;
} else if(x->val > val) {
Remove(x->left, val);
} else Remove(x->right, val);
}
void print(node *d) {
if(d->left) print(d->left);
if(d->right) print(d->right);
printf("%d ", d->val);
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
scanf("%d", &n);
int x;
for(int i = 0; i < n; ++i) {
scanf("%d", &x);
Insert(x);
print(root); printf("\n");
}
scanf("%d", &m);
for(int i = 0; i < m; ++i) {
scanf("%d", &x);
Remove(root, x);
print(root); printf("\n");
}
return 0;
}