请教大佬们深基示例代码
查看原帖
请教大佬们深基示例代码
1067279
coolwind楼主2024/3/21 22:53
#include <iostream>
int n, cnt, root, opt, x;
struct Node {
    int right, left, value, size, num;
    Node (int l, int r, int s, int v) : right{r} , left{l}, value{v}, size{s} , num{1} {}
    Node() = default;
} t[100010];

inline void update(int root)
{
    t[root].size = t[t[root].left].size + t[t[root].right].size + t[root].num;
}

int rank(int x, int root)
{
    if (root)
    {
        if (x < t[root].value)
            return rank(x,t[root].left);
        if (x > t[root].value)
            return rank(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)
{
    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)
{
    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++;
    update(root);
}

int main()
{
    std::cin >> n;
    int num {};
    t[root = ++cnt] = Node {0,0,1,2147483647};
    while (n--)
    {
        std::cin >> opt >> x;
        num++;
        if (opt == 1)
            std::cout << rank(x,root) << std::endl;
        else if (opt == 2)
            std::cout << kth(x,root) << std::endl;
        else if (opt == 3)
            std::cout << kth(rank(x,root) - 1,root) << std::endl;
        else if (opt == 4)
            std::cout << kth(rank(x+1,root),root) << std::endl;
        else
        {
            num--;
            insert(x,root);
        }
    }
    
}

以上是深基示例代码,主要是想问大佬们在操作3和4查找前驱后继,为什么找前驱是先rank找到x的排名的前一位,而后继则是查找x+1的排名? 我尝试过都改成rank(x)+1,rank(x)-1或者rank(x+1),rank(x-1)都不行? 这和上面查找rank的实现有关吗还是这个树的建立有问题qwq

2024/3/21 22:53
加载中...