版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Q1410136042/article/details/82561392
一、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 Node(x);
}
else
{
int d = o->cmp(x);
insert(o->ch[d], x);
if(o->ch[d]->r > o->r)
rotate(o, d^1);
}
}
void remove(Node* &o, int x)
{
int d= o->cmp(x);
if(d == -1)
{
if(o->ch[0] == NULL) o = o->ch[1];
else if(o->ch[1] = NULL) o = o->ch[0];
else
{
int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
rotate(o, d2);
remove(o->ch[d2], x);
}
}
else
remove(o->ch[d], x);
}
int find(Node* o, int x)//调用插入和删除前需要先find()是否存在
{
while(o != NULL)
{
int d = o->cmp(x);
if(d == -1) return 1;//存在
else o = o->ch[d];
}
return 0;//不存在
}
二、Rank Tree
名次树可以由Treap实现,树如其名,它在Treap的基础上增加了两个功能:
- Kth(k):查找第k小的元素
- Rank(x):x的名次,即x是第几小的元素
它的实现主要是在Treap的Node里增加一个size域,表示以它为根的子树的总结点数,并且增加一个maintain()操作,用于计算size,在旋转,删除,插入等操作后都需要调用maintain()来更新size()
代码如下:
// 使用Treap实现Rank Tree
#include<bits/stdc++.h>
struct Node // Rank Tree结点的定义
{
Node* ch[2];// 左右子树
int r, v; // 优先级(越大,优先级越高)和键值
int s; // 以它为根的子树的总结点数
Node(int v=0):v(v) { ch[0] = ch[1] = NULL; r = rand(); s = 1;}//注意要初始化随机种子srand(time(0))
int cmp(const int& x) const
{
if(x == v) return -1;
return x < v ? 0 : 1;
}
void maintain()
{
s = 1;
if(ch[0] != NULL) s += ch[0]->s;
if(ch[1] != NULL) s += ch[1]->s;
}
};
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->maintain();
k->maintain();
o = k;
}
void insert(Node* &o, int x)//在以o为根的子树插入键值x,修改o
{
if(o == NULL)
o = new Node(x);
else
{
int d = (x < o->v ? 0 : 1);
insert(o->ch[d], x);
if(o->ch[d]->r > o->r)
rotate(o, d^1);
}
o->maintain();
}
void remove(Node* &o, int x)
{
int d= o->cmp(x);
if(d == -1)
{
if(o->ch[0] == NULL) o = o->ch[1];
else if(o->ch[1] = NULL) o = o->ch[0];
else
{
int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
rotate(o, d2);
remove(o->ch[d2], x);
}
}
else
remove(o->ch[d], x);
if(o != NULL) o->maintain();
}
int kth(Node* o, int k)
{
if(o == NULL || k > o -> s || k <= 0) return 0;
int s = (o -> ch[0] == NULL ? 0 : o -> ch[0] -> s);
if(k == s + 1) return o -> v;
else if(k <= s) return kth(o -> ch[0], k);
else return kth(o -> ch[1], k - s - 1);
}
int rank(Node* o, int x)
{
if(o == NULL) return 0;
int res = 0;
int s = (o -> ch[0] == NULL ? 0 : o -> ch[0] -> s);
if(x <= o -> v)
{
res += rank(o -> ch[0], x);
res += x == o -> v;
}
else
{
res += s + 1;
res += rank(o -> ch[1], x);
}
return res;
}