题解 | 动态整数集最近值提取

动态整数集最近值提取

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

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

set<int> st;
int Q;

int main(){
	
	cin>>Q;
	int op,x;
	while(Q--){
		cin>>op>>x;
		if(op==1){
			if(st.count(x)!=0){
				cout<<"Already Exist"<<endl;
			}else{
				st.insert(x);
			}
		}else if(op==2){
			if(st.empty()){
				cout<<"Empty"<<endl;
				continue;
			}
            if(x<=*st.begin()){
                cout<<*st.begin()<<endl;
                st.erase(*st.begin());
                continue;
            }else if(x>=*(--st.end())){
                cout<<*(--st.end())<<endl;
                st.erase(*(--st.end()));
                continue;
            }
			auto it=st.lower_bound(x);
			
			int n1=abs((*it)-x);--it;
            int n2=abs((*it)-x);++it;
			if(n1<n2){
				cout<<*it<<endl;
				st.erase(*it);	
			}else{
				it--;
				cout<<*it<<endl;
				st.erase(*it);
			}
		}
	}

    return 0;
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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