P5076 【深基16.例7】普通二叉树(简化版)

题目描述

您需要写一种数据结构,来维护一些数( 都是 10^9109 以内的数字)的集合,最开始时集合是空的。其中需要提供以下操作,操作次数 qq 不超过 10^4104:

  1. 查询 xx 数的排名(排名定义为比当前数小的数的个数 +1+1。若有多个相同的数,应输出最小的排名)。
  2. 查询排名为 xx 的数。
  3. 求 xx 的前驱(前驱定义为小于 xx,且最大的数)。若未找到则输出 -2147483647−2147483647。
  4. 求 xx 的后继(后继定义为大于 xx,且最小的数)。若未找到则输出 21474836472147483647。
  5. 插入一个数 xx。

输入格式

输出格式

输入输出样例

输入 #1复制

7
5 1
5 3
5 5
1 3
2 2
3 3
4 3

输出 #1复制

2
3
1

        二叉树的遍历,查找,增加值,注意递归的调用。

#include <iostream>
#define maxn 100010
using namespace std;
int n, root, cnt, m, x;//root为根节点
struct Node {
    int left, right, size, value, num;
    Node(int l,int r,int s,int v):
        left(l),right(r),size(s),value(v),num(1){}
    Node(){}//设置结点,初始化该结构体
}t[maxn];
inline void ud(int root) {//inline 需反复不停的调用该函数时,则可以用
    t[root].size = t[t[root].left].size + t[t[root].right].size + t[root].num;//更新结点
}
int rk(int x, int root) {
    if (root) {
        if (x < t[root].value) {
            return rk(x, t[root].left);
        }
        if (x >t[root].value) {
            return rk(x, t[root].right)+t[t[root].left].size+t[root].num;
        }
        return t[t[root].left].size + t[root].num;
    }
    return 1;
}
int kth(int x, int root) {//查找排名x的值
    if (x <= t[t[root].left].size) {
        return kth(x, t[root].left);
    }
    if (x <= t[t[root].left].size + t[root].num) {
        return t[root].value;
    }
    return kth(x-t[t[root].left].size -t[root].num,t[root].right);//减去左子树和根节点,遍历右子树
}
void insert(int x, int& root) {//增加x的结点。
    if (x < t[root].value) {
        if (!t[root].left) {//左子树结点为空
            t[t[root].left = ++cnt] = Node(0, 0, 1, x);//建立新节点
        }
        else {
            insert(x, t[root].left);//继续向左子树搜索。
        }
    }
    else if (x > t[root].value) {
        if (!t[root].right) {//右子树结点为空
            t[t[root].right = ++cnt] = Node(0, 0, 1, x);//建立新节点
        }
        else {
            insert(x, t[root].right);//继续向右子树搜索。
        }
    }
    else {
        t[root].num++;//根节点增加
        
    }
    ud(root);//更新新结点
}
int main()
{
    cin >> n;
    int num = 0;
    t[root = ++cnt] = Node(0, 0, 1, 2147483647);
    while (n--) {
        cin >> m >> x;
        num++;
        if (m == 1)cout << rk(x, root) << endl;
        else if (m == 2) cout << kth(x, root) << endl;
        else if (m == 3)cout << kth(rk(x, root) - 1, root) << endl;//前驱节点
        else if (m == 4)cout << kth(rk(x + 1, root), root) << endl;//后继节点
        else {
            num--;
            insert(x, root);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钟一淼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值