一、Treap
简单地说,Treap是一棵拥有键值、优先级两种权值的树。对于键值而言,它是BST,对于优先级而言,它是堆。它的插入、删除和查找的期望时间复杂度均为O(log n)
它在插入的时候,随机生成一个优先级,首先根据键值以BST的方式插入到Treap里,然后通过BST的旋转来维护优先级堆的性质,而旋转本身是不会破坏BST的性质的,这就保证了插入完成之后,仍然是一棵Treap
其它的没什么好说的,代码如下:
struct Node // Treap结点的定义
{
Node* ch[2]; // 左右子树
int r, v; // 优先级(越大,优先级越高)和键值
Node(int v=0):v(v) { ch[0] = ch[1] = NULL; r = rand();}//注意要初始化随机种子srand(time(0))
int cmp(const int& x) const
{
if(x == v) return -1;
return x < v ? 0 : 1;
}
};
void rotate(Node* &o, int d)//d=0代表左旋,d=1代表右旋,最终o仍然指向根
{
Node* k = o->ch[d^1];
o->ch[d^1] = k->ch[d];
k->ch[d] = o;
o = k;
}
void insert(Node* &o, int x)//在以o为根的子树插入键值x,修改o
{
if(o == NULL)
{
o = new Nod