洛谷P5076 【深基16.例7】普通二叉树(简化版)
- 查询 �x 数的排名(排名定义为比当前数小的数的个数 +1+1。若有多个相同的数,应输出最小的排名)。
- 查询排名为 �x 的数。
- 求 �x 的前驱(前驱定义为小于 �x,且最大的数)。若未找到则输出 −2147483647−2147483647。
- 求 �x 的后继(后继定义为大于 �x,且最小的数)。若未找到则输出 21474836472147483647。
- 插入一个数 �x。
第一行是一个整数 �q,表示操作次数。
接下来 �q 行,每行两个整数 ��,�op,x,分别表示操作序号以及操作的参数 �x。
BST模板?
#include<bits/stdc++.h>//万能头文件
using namespace std; //命名空间
int cnt = 1;
struct node{
int left, right; //左右子树
int value; //节点存的值
int num; //重复值有多少个
int size; //左右子树及自己的节点和
}t[10005];
void insert(int x, int root){
if(cnt == 1){
node tmp = {0,0,x,1,1};
t[cnt] = tmp;
cnt++;
}else{
if(x < t[root].value){
if(t[root].left == 0){
node tmp = {0,0,x,1,1};
t[cnt] = tmp;
t[root].left = cnt;
cnt++;
}else insert(x, t[root].left);
}
if(x == t[root].value) t[root].num++;
if(x > t[root].value){
if(t[root].right == 0){
node tmp = {0,0,x,1,1};
t[cnt] = tmp;
t[root].right = cnt;
cnt++;
}else insert(x, t[root].right);
}
}
t[root].size = t[t[root].left].size + t[t[root].right].size + t[root].num;
}
int query1(int x, int root){ //查找数字x的排名
if(root == 0) return 1;
if(x < t[root].value) return query1(x,t[root].left);
if(x == t[root].value) return t[t[root].left].size + 1;
if(x > t[root].value) return t[t[root].left].size + t[root].num + query1(x,t[root].right);
}
int query2(int x, int root){ //查找排名为x的数字是什么
if(x <= t[t[root].left].size) return query2(x,t[root].left);
if(x <= t[t[root].left].size + t[root].num) return t[root].value;
return query2(x-t[t[root].left].size-t[root].num, t[root].right);
}
int main(){
int n, op, x;
cin >> n;
for(int i = 0; i < n; i++){
cin >> op >> x;
if(op == 1) cout << query1(x,1) << endl;
if(op == 2) cout << query2(x,1) << endl;
if(op == 3){
int tmp = query1(x,1);
if(tmp == 1) cout << -2147483647 << endl;
else cout << query2(tmp - 1, 1) << endl;
}
if(op == 4){
int tmp = query1(x + 1,1);
if(tmp == cnt) cout << 2147483647 << endl;
else cout << query2(tmp, 1) << endl;
}
if(op == 5) insert(x,1);
}
return 0;
}