#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <stdlib.h>
using namespace std;
struct Node {
Node *ch[2];
int priority;
int val;
int cmp(int x) const {
if (val == x) return -1;
return x < val ? 0 : 1;
}
};
class Treap {
public:
Node *root;
Treap() {root = NULL;}
void rotate(Node *&o, int d) {
// d: 0, then rotate left
// d: 1, then rotate right
Node *k = o->ch[d^1];
if (k == NULL) return;
o->ch[d^1] = k->ch[d];
k->ch[d] = o;
o = k;
}
int random() {
return rand() % 57;
}
void insert(Node *&o, int val) {
if (o == NULL) {
o = new Node(); o->val = val; o->priority = random(); o->ch[0] = o->ch[1] = NULL;
} else {
int d = o->cmp(val);
insert(o->ch[d], val);
if (o->ch[d]->priority < o->priority) rotate(o, d^1);
}
}
void remove(Node *&o, int val) {
if (o == NULL) return;
if (o->cmp(val) == -1) {
if (o->ch[0] == NULL) o = o->ch[1];
else if (o->ch[1] == NULL) o = o->ch[0];
else {
int d = o->ch[0]->priority < o->ch[1]->priority?0:1;
rotate(o, d^1);
remove(o->ch[d^1], val);
}
} else {
remove(o->ch[o->cmp(val)], val);
}
}
Node* find(Node *o, int val) {
while (o != NULL) {
int d = o->cmp(val);
if (d == -1) return o;
o = o->ch[d];
}
return NULL;
}
};
int main() {
Treap t;
int sz[6] = {2, 4, 5, 7, 9, 10};
for (int i = 0; i < 6; i++) t.insert(t.root, sz[i]);
t.remove(t.root, 7);
return 0;
}
Treap Demo
最新推荐文章于 2021-08-09 14:49:53 发布