一开始以为输入的数只和前面的数有关,依旧是语文吃大亏的一天,实际上是输入一次更新一次,也就是维持一个升序序列。

输入一次sort一次是肯定会超时的(想都不用想)

题目说是集合,而且元素可以重复,那就直接multiset!

AC代码(STL大法好)

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

multiset<int>s;
int q,op,x;

int main(){
    scanf("%d",&q);
    //加入前驱和后缀
    s.insert(INT_MAX);
    s.insert(INT_MIN);
    for(int i=1;i<=q;i++){
        scanf("%d %d",&op,&x);
        if(op==1){
            int rank=0;
            auto it=s.lower_bound(x);
            auto j=s.begin();
            while(j!=it)j++,rank++;
            cout<<rank<<endl;
        }else if(op==2){
            int rank=-1;
            for(auto j:s){
                if(++rank==x){
                    cout<<j<<endl;
                    break;
                }
            }
        }else if(op==3){
            auto it=s.lower_bound(x);
            cout<<*--it<<endl;
        }else if(op==4){
            cout<<*s.upper_bound(x)<<endl;
        }else if(op==5){
            s.insert(x);
        }
    }
    return 0;
}

如果不用upper_bound和lower_bound的内置二分查找,直接for会超时。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐