题解 | 动态整数集最近值提取|注意x超出集合范围的情况

动态整数集最近值提取

https://www.nowcoder.com/practice/c8615a370bb24ce6b110c3d7151c3dfc

#include<bits/stdc++.h>
using namespace std;
set<int> s;
int main(){
    int n;
    cin>>n;
    while(n--){
        int op,x;
        cin>>op>>x;
        if(op==1){
            if(s.count(x)==0) s.insert(x);
            else cout<<"Already Exist"<<endl;
        }
        if(op==2){
            if(!s.empty()){
                if(x<=*s.begin()){
                    cout<<*s.begin()<<endl;
                    s.erase(*s.begin());
                    continue;
                }else if(x>=*--s.end()){
                    cout<<*--s.end()<<endl;
                    s.erase(*--s.end());
                    continue;
                }
                int qq,hj;
                auto it=s.lower_bound(x);
                hj=*it;
                qq=*--it;
                if((x-qq)>(hj-x)){
                    cout<<hj<<endl;
                    s.erase(hj);
                }else{
                    cout<<qq<<endl;
                    s.erase(qq);
                }
            }else{
                cout<<"Empty"<<endl;
            }
        }
    }
    return 0;
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务