# Luogu P5076 [Basic 16. Example 7] Ordinary Binary Tree (Simplified Version) Solution

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/luogu-p5076-binary-tree-simplified-solution/>). I am continuously working to improve the translation.

> # P5076 [Basic 16. Example 7] Ordinary Binary Tree (Simplified Version)
>
> ## Problem Description
>
> You need to write a data structure to maintain a set of numbers (all with absolute values within $10^9$). The set is initially empty. It must support the following operations, with the number of operations $q$ not exceeding $10^4$:
>
> 1. Define the rank of a number $x$ as the count of numbers in the set that are less than $x$, plus $+1$. Query the rank of number $x$. **Note that $x$ is not necessarily in the set**.
> 2. Query the number with rank $x(x\ge 1)$. **It is guaranteed that the set contains at least $x$ numbers**.
> 3. Find the predecessor of $x$ (the predecessor is defined as the largest number less than $x$). If it does not exist, output $-2147483647$.
> 4. Find the successor of $x$ (the successor is defined as the smallest number greater than $x$). If it does not exist, output $2147483647$.
> 5. Insert a number $x$. The data of this problem guarantees that $x$ is not in the set before insertion.
>
> It is guaranteed that when operations $1,3,4$ are executed, the set contains at least one element.
>
> ## Input Format
>
> The first line contains an integer $q$, the number of operations.
>
> The next $q$ lines each contain two integers $op,x$, representing the operation index and the parameter $x$ of the operation, respectively.
>
> ## Output Format
>
> The output consists of several lines. For operations $1,2,3,4$, output an integer representing the result of that operation.
>
> ## Sample Input and Output #1
>
> ### Input #1
>
> ```TEXT
> 7
> 5 1
> 5 3
> 5 5
> 1 3
> 2 2
> 3 3
> 4 3
> ```
>
> ### Output #1
>
> ```TEXT
> 2
> 3
> 1
> 5
> ```

# Solutions

## Method 1

Use a BST

An implementation is as follows

```cpp
#include<bits/stdc++.h>
using namespace std;

using i64=long long;
using u64=unsigned long long;
using u32=unsigned;
using u128=unsigned __int128;

const int inf=2147483647;

//需要实现：按照排名找权值，按照权值找排名，找前驱，找后继，插入
struct node{
    int v;
    int lchild=0,rchild=0;
    int siz; //(两子树 + 自己本身) 的大小（结点数之和）
}bst[100010]; //以 1 为根结点

int cnt=0; //表示总结点数目

void insert(int v,int idx){ //v 表示权值，idx 表示当前的结点编号
    bst[idx].siz++;
    if(v>bst[idx].v){ //说明 v 应该插入到右子树
        if(bst[idx].rchild!=0){
            insert(v,bst[idx].rchild);
        }
        else{ //不存在右孩子
            cnt++;
            bst[cnt].v=v;
            bst[cnt].siz=1;
            bst[idx].rchild=cnt;
        }
    }
    else{
        if(bst[idx].lchild!=0){
            insert(v,bst[idx].lchild);
        }
        else{
            cnt++;
            bst[cnt].v=v;
            bst[cnt].siz=1;
            bst[idx].lchild=cnt;
        }
    }
}

int findPre(int v){
    int idx=1; //从根结点开始搜索
    int ans=-inf;
    while(idx){
        if(bst[idx].v<v){
            ans=bst[idx].v;
            idx=bst[idx].rchild;
        }
        else{
            idx=bst[idx].lchild;
        }
    }
    return ans;
}

int findPost(int v){
    int idx=1;
    int ans=inf;
    while(idx){
        if(bst[idx].v>v){
            ans=bst[idx].v;
            idx=bst[idx].lchild;
        }
        else{
            idx=bst[idx].rchild;
        }
    }
    return ans;
}

int fromRankfindV(int rk,int idx){ //idx 是当前遍历到的根结点
    int leftSize=bst[bst[idx].lchild].siz;
    if(rk<=leftSize){
        return fromRankfindV(rk,bst[idx].lchild);
    }
    else if(rk==leftSize+1){
        return bst[idx].v;
    }
    else{
        return fromRankfindV(rk-leftSize-1,bst[idx].rchild);
    }
    
}

//标准做法
int fromVfindRank(int v,int idx){ //最后返回值还需要再 +1
    if(idx==0) return 0;
    if(v<=bst[idx].v){
        return fromVfindRank(v,bst[idx].lchild);
    }
    else{
        return bst[bst[idx].lchild].siz+1+fromVfindRank(v,bst[idx].rchild);
    }
}

int main(){
    ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);

    int q;
    cin>>q;

    while(q--){
        int op;
        int x;
        cin>>op>>x;
        if(op==1){
            cout<<fromVfindRank(x,1)+1<<"\n";
        }
        else if(op==2){
            cout<<fromRankfindV(x,1)<<"\n";
        }
        else if(op==3){
            cout<<findPre(x)<<"\n";
        }
        else if(op==4){
            cout<<findPost(x)<<"\n";
        }
        else if(op==5){
            if(cnt==0){
                cnt=1;
                bst[1].v=x;
                bst[1].siz=1;
            }
            else insert(x,1);
        }
    }

    return 0;
}
```

However, the functions for finding the predecessor and successor can be omitted, because we can first query the rank of x, then query the numbers with rank-1 and rank+1, which are exactly the predecessor and successor respectively.

If rank+1>cnt or rank-1<1, then we can output inf and -inf respectively.

## Method 2

Use the STL container multiset

> ## A Detailed Explanation of Common Uses of multiset
>
> ### Definition of multiset
>
> `multiset` is a container that can store multiple identical elements. In other words, if you have a bunch of duplicate numbers, such as 3, 5, 5, 5, 7, you can use a `multiset` to manage them properly. `set` does not allow duplicate elements. Unlike `set`, `multiset` warmly welcomes the addition of duplicate elements.
>
> It can be created using elements with uniform initialization
>
> ```cpp
> int main() {
>     multiset<int> numbers = {3, 5, 5, 7, 3, 9};
> 
>     // 基于范围的 for 循环遍历 multiset
>     for (int num : numbers) {
>         cout << num << " ";
>     }
> 
>     return 0;
> }
> ```
>
> **Note that `multiset` automatically arranges elements in ascending order.**
>
> **If it is a custom type, the less-than operator must be overloaded**
>
> ### Accessing Elements in a multiset
>
> Use iterators
>
> ### Analysis of Common multiset Functions
>
> #### insert()
>
> Omitted
>
> #### erase()
>
> The `erase` method is used to delete elements. But be careful! If you pass in a value directly, all elements equal to that value will be deleted. If you only want to delete a specific element, it is best to first find its iterator and then use that iterator to delete it.
>
> ```cpp
> int main() {
>     multiset<int> numbers = {3, 5, 5, 7};
> 
>     // 删除所有的 5
>     numbers.erase(5);
> 
>     // 打印当前的 multiset
>     for (int num : numbers) {
>         cout << num << " ";
>     }
> 
>     return 0;
> }
> ```
>
> If you only want to delete the first 5
>
> ```cpp
> auto it = numbers.find(5);  // 找到第一个 5
> if (it != numbers.end()) {
>     numbers.erase(it);  // 只删除找到的第一个 5
> }
> ```
>
> #### size()
>
> Omitted
>
> #### clear()
>
> Omitted
>
> #### empty()
>
> Omitted
>
> #### lower_bound()
>
> Omitted **It is different from the one in algorithm**
>
> #### upper_bound()
>
> Omitted **It is different from the one in algorithm**

### Analyzing the Problem

#### 1. Query the rank of number x

The rank, simply put, is the index of x after sorting.

We just need to use the lower_bound method to find the position of the first x.

Then iterate through the container from begin; once we reach that position, we output the current index.

#### 2. Query the number with rank x

Iterate through the container; once the current rank reaches x, output the current value.

(Because the multiset container does not support random access)

#### 3. Find the predecessor of x (the predecessor is defined as the largest number less than x)

The predecessor is simply the element before x.

We just need to use the lower_bound method to find the position of the first x, and then output the previous one — done.

#### 4. Find the successor of x (the successor is defined as the smallest number greater than x).

The successor is simply the first number greater than x.

We can use the upper_bound method to find this value directly.

#### 5. Insert a number x

Simply insert it using the insert method.

```cpp
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<set>
using namespace std;
multiset<int>q;
int n,t,x,order;
int main()
{
    q.insert(-0x7fffffff);
    q.insert(0x7fffffff);
    //提前放入这两个数，避免错误
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d%d",&t,&x);
        if(t==1)
        {
            auto it=q.lower_bound(x);
            //可以写作 multiset<int>::iterator，因为 lower_bound 方法返回的是迭代器
            // it 取得 x 的位置
            
            order=0;
            //order 为排名
            
            for(auto i=q.begin();i!=it;i++,order++);
            //这里就处理出了 x 的排名——order
            
            printf("%d\n",order);
            //输出 order 即为答案
        }
        else if(t==2)
        {
            order=-1;
            //初值为 -1 是因为前面有一个 -0x7fffffff，所以 order 要多跑一步

            for(int i:q)
                if(++order==x)
                //缩写，order 先自增一，再判断是否与 x 相等
                //如果是 (order++==x)，那就是先判断再自增，这里要尤其注意
                    printf("%d\n",i);
                //i 就是容器里的值，输出 i
        }
        else if(t==3)
        {
            auto it=q.lower_bound(x);
            //取得第一个大于等于 x 的值
            //也就是第一个 x 的位置
            //由于我们要取得前驱，所以 it 要自减一
            printf("%d\n",*--it);
            //这句是先自减，再输出，是缩写
            //等价于：
            /*
                it--;
                printf("%d\n",*it);
            */
            //因为是迭代器（指针），所以输出前面加 *
        }
        else if(t==4)
        {
            printf("%d\n",*q.upper_bound(x));
            //要取得后继，就是第一个大于 x 的值
            //用 upper_bound 方法取得第一个大于 x 的迭代器
            //输出即可
            //因为是迭代器（指针），所以输出前面加 *
        }
        else
        {
            q.insert(x);
            //直接添加即可
        }
    }
    return 0;
}
```
