Treap Demo

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值