Treap包含了二叉查找树和堆的特性,而且性价比很高!
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int INF = ~0U >> 1;
struct node {
node *left, *right;
int val, fix;
};
struct node *root;
void LeftRotate(node *& a) {
node *b = a->right;
a->right = b->left;
b->left = a;
a = b;
}
void RightRotate(node *& a) {
node *b = a->left;
a->left = b->right;
b->right = a;
a = b;
}
void Insert(node *&p, int val) {
if(p == NULL) {
p = new node;
p->left = p->right = NULL;
p->val = val;
p->fix = rand();
} else if(p->val > val) {
Insert(p->left, val);
if(p->fix > p->left->fix) RightRotate(p);
} else {
Insert(p->right, val);
if(p->fix > p->right->fix) LeftRotate(p);
}
}
void Delete(node *&p, int val) {
if(p->val == val) {
if(!p->left || !p->right) {
node *t = p;
if(!p->left) p = p->right;
else p = p->left;
delete t;
} else {
if(p->right->fix > p->left->fix) {
RightRotate(p);
Delete(p->right, val);
}
else {
LeftRotate(p);
Delete(p->left, val);
}
}
} else if(p->val > val) {
Delete(p->left, val);
} else Delete(p->right, val);
}
void print(node *a) {
if(a->left) print(a->left);
if(a->right) print(a->right);
printf("%d ", a->val);
return ;
}
int main() {
int m, n, x;
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", &x);
Insert(root, x);
print(root);
printf("\n");
}
scanf("%d", &m);
for(int i = 0; i < m; ++i) {
scanf("%d", &x);
Delete(root, x);
print(root);
printf("\n");
}
}