描述
小Ho:小Hi,我发现我们以前讲过的两个数据结构特别相似。
小Hi:你说的是哪两个啊?
小Ho:就是二叉排序树和堆啊,你看这两种数据结构都是构造了一个二叉树,一个节点有一个父亲和两个儿子。 如果用1..n的数组来存储的话,对于二叉树上的一个编号为k的节点,其父亲节点刚好是k/2。并且它的两个儿子节点分别为k*2和k*2+1,计算起来非常方便呢。
小Hi:没错,但是小Hi你知道有一种办法可以把堆和二叉搜索树合并起来,成为一个新的数据结构么?
小Ho:这我倒没想过。不过二叉搜索树满足左子树<根节点<右子树,而堆是满足根节点小于等于(或大于等于)左右儿子。这两种性质是冲突的啊?
小Hi:恩,你说的没错,这两种性质的确是冲突的。
小Ho:那你说的合并是怎么做到的?
小Hi:当然有办法了,其实它是这样的….
提示:Tree+Heap?
输入
第1行:1个正整数n,表示操作数量,10≤n≤100,000
第2..n+1行:每行1个字母c和1个整数k:
若c为’I’,表示插入一个数字k到树中,-1,000,000,000≤k≤1,000,000,000
若c为’Q’,表示询问树中不超过k的最大数字
输出
若干行:每行1个整数,表示针对询问的回答,保证一定有合法的解
样例输入
5
I 3
I 2
Q 3
I 5
Q 4
样例输出
3
3
题目:这里写链接内容
思路:Treap模板题,手动实现一个lower函数。
#include<cstdio>
#include<algorithm>
#include <ctime>
#include <limits.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn =30100;
struct Treap {
struct node {
ll key, weight, cnt, size;
node *childs[2];
void init(ll x) {
key = x;
weight = rand();
cnt = 1;
size = 1;
childs[0] = childs[1] = NULL;
}
};
node *root;
void update(node *&x) {
if (x == NULL)
return;
int right = 0, left = 0;
if (x->childs[0] != NULL)right = x->childs[0]->size;
if (x->childs[1] != NULL)left = x->childs[1]->size;
x->size = right + left + x->cnt;
}
void rotate(node *&x, int t) {
node *y = x->childs[t];
x->childs[t] = y->childs[1 - t];
y->childs[1 - t] = x;
update(x);
update(y);
x = y;
}
void _insert(node *&x, ll k) {
if (x != NULL) {
if (x->key == k) {
x->cnt++;
} else {
int t = x->key < k;
_insert(x->childs[t], k);
if (x->childs[t]->weight < x->weight) {
rotate(x, t);
}
}
} else {
x = (node *) malloc(sizeof(node));
x->init(k);
}
update(x);
}
void _erase(node *&x, ll k) {
if (x->key == k) {
if (x->cnt > 1) {
x->cnt--;
} else {//如果被删除节点存在子节点,先将其旋转至底层再删除
if (x->childs[0] == NULL && x->childs[1] == NULL) {
x->cnt = 0;
return;
}
int t;
if (x->childs[0] == NULL)t = 1;
else if (x->childs[1] == NULL)t = 0;
else t = x->childs[0] > x->childs[1];
rotate(x, t);
_erase(x, k);
}
} else {
int t = x->key < k;
_erase(x->childs[t], k);
if (x->childs[t]->cnt == 0)free(x->childs[t]), x->childs[t] = NULL;//动态内存释放
}
update(x);
}
ll _getkth(node *&x, ll k) {
int t = 0;
if (x->childs[0] != NULL)t = x->childs[0]->size;
if (k <= t)return _getkth(x->childs[0], k);
k -= t + x->cnt;
if (k <= 0)return x->key;
return _getkth(x->childs[1], k);
}
void _lower(node *&x,ll k,ll &ans){
if(x->key<=k){
ans=max(ans,x->key);
if(x->childs[1]!=NULL)_lower(x->childs[1],k,ans);
}else if(x->childs[0]!=NULL)_lower(x->childs[0],k,ans);
}
void insert(ll k) {
_insert(root, k);
}
void erase(ll k) {
_erase(root, k);
}
ll getkth(ll k) {
return _getkth(root, k);
}
void lower(ll k,ll &ans){
_lower(root,k,ans);
}
};
Treap tree;
int main() {
//srand((unsigned int)time(NULL));
int n;
scanf("%d%d",&n);
for(int i=1;i<=n;i++){
char c;
ll k;
scanf(" %c%lld",&c,&k);
if(c=='I')tree.insert(k);
else {
ll ans=-1000000100;
tree.lower(k,ans);
printf("%lld\n",ans);
}
}
return 0;
}