马蜂

BST

#include<bits/stdc++.h>
using namespace std;
int node_num;
const int MAX = 2147483647;

struct node{
    int val, l, r, cnt, size;
};  node tree[400005];

void add(int x, int p){
    tree[p].size++;
    if(tree[p].val == x){
        tree[p].cnt++;
        return ;
    }
    if(tree[p].val <= x){
        if(tree[p].r == 0){
            node_num++;
            tree[p].r = node_num;   
            tree[node_num].val = x, tree[node_num].size = tree[node_num].cnt = 1;
        }else{
            add(x, tree[p].r);
        }
    }else{
        if(tree[p].l == 0){
            node_num++;
            tree[p].l = node_num;
            tree[node_num].val = x, tree[node_num].size = tree[node_num].cnt = 1;
        }else{
            add(x, tree[p].l);
        }
    }
}

int qianqu(int x, int p, int ans){
    if(tree[p].val >= x){
        if(!tree[p].l)  return ans;
        return qianqu(x, tree[p].l, ans);
    }else{
        if(!tree[p].r){
            if(tree[p].val >= x)    return ans;
            return tree[p].val;
        }
        return qianqu(x, tree[p].r, tree[p].val);
    }
}

int houqu(int x, int p, int ans){
    if(tree[p].val <= x){
        if(!tree[p].r)  return ans;
        return houqu(x, tree[p].r, ans);
    }else{
        if(!tree[p].l){
            if(tree[p].val <= x)    return ans;
            return tree[p].val;
        }
        return houqu(x, tree[p].l, tree[p].val);
    }
}

int Q(int x, int p){
    if(!p)  return 0;
    if(tree[p].val == x)    return tree[tree[p].l].size;
    if(tree[p].val <= x)    return Q(x, tree[p].r) + tree[tree[p].l].size + tree[p].cnt;
    return Q(x, tree[p].l); 
}

int q(int p, int rk){
    if(p == 0)  return MAX;
    if(tree[tree[p].l].size >= rk)  return q(tree[p].l, rk);
    if(tree[tree[p].l].size + tree[p].cnt >= rk)    return  tree[p].val;
    return q(tree[p].r, rk - tree[tree[p].l].size - tree[p].cnt);
}

void print(int p){
    if(!p)  return ;
    cout<<tree[p].val<<endl;
    print(tree[p].l);
    print(tree[p].r);
}

int main()
{
    int t;
    cin>>t;
    while(t--){
        int op, x;
        cin>>op>>x;
        if(op == 1) cout<<Q(x, 1)+1<<endl;
        if(op == 2) cout<<q(1, x)<<endl;
        if(op == 3) cout<<qianqu(x, 1, -MAX)<<endl;
        if(op == 4) cout<<houqu(x, 1, MAX)<<endl;
        if(op == 5){
            if(node_num == 0){
                node_num++;
                tree[1].cnt = tree[1].size = 1;
                tree[1].val = x;
            }else{
                add(x, 1);
            }
        }
    }
//  print(1);
    return 0;
}
posted @ 2021-08-27 09:47  WRuperD  阅读(1)  评论(0编辑  收藏  举报  来源

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

这是一条自定义内容

这是一条自定义内容