14 分求助
查看原帖
14 分求助
932039
lzy20091001楼主2023/9/24 23:32

https://www.luogu.com.cn/record/126028774

样例已过,请问为什么会这样 QwQ

#include <iostream>
using namespace std;

struct Btree
{
    int data;
    Btree *lchild, *rchild;
};

int SizeBST(Btree *t)
{
    if (t == NULL)
        return 0;
    return SizeBST(t->lchild) + SizeBST(t->rchild) + 1;
}

int RankBST(Btree *t, int x)
{
    if (t == NULL)
        return 1;
    if (x == t->data)
        return SizeBST(t->lchild) + 1;
    else if (x < t->data)
        return RankBST(t->lchild, x);
    else
        return RankBST(t->rchild, x) + SizeBST(t->lchild) + 1;
}

int FindBST(Btree *t, int x)
{
    if (t == NULL)
        return -1;
    if (x == SizeBST(t->lchild) + 1)
        return t->data;
    else if (x <= SizeBST(t->lchild))
        return FindBST(t->lchild, x);
    else
        return FindBST(t->rchild, x - SizeBST(t->lchild) - 1);
}

void InsertBST(Btree *&t, int x)
{
    if (t == NULL)
    {
        Btree *s = new Btree;
        s->data = x;
        s->lchild = s->rchild = NULL;
        t = s;
    }
    if (x < t->data)
        InsertBST(t->lchild, x);
    else if (x > t->data)
        InsertBST(t->rchild, x);
}

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

    Btree *tree = NULL;
    int q, op, x;
    cin >> q;
    while (q--)
    {
        cin >> op >> x;
        if (op == 1)
            cout << RankBST(tree, x) << "\n";
        else if (op == 2)
            cout << FindBST(tree, x) << "\n";
        else if (op == 3)
        {
            int ans = FindBST(tree, RankBST(tree, x) - 1);
            if (ans == -1)
                cout << -2147483647 << "\n";
            else
                cout << ans << "\n";
        }
        else if (op == 4)
        {
            int ans = FindBST(tree, RankBST(tree, x) + 1);
            if (ans == -1)
                cout << 2147483647 << "\n";
            else
                cout << ans << "\n";
        }
        else
            InsertBST(tree, x);
    }
    return 0;
}

2023/9/24 23:32
加载中...