复习了一下set是个什么,顺带学了一下指针
总共两个指令,1插入,2查询并删除
- 插入:直接set的insert插入即可,注意重复要输出Already Exist
- 查询并删除:首先判断是否为空,然后用lower_bound找第一个大于等于的元素,如果找到结尾说明全都小于,end()前一个就是要的,如果找到开头,说明全都大于,第一个元素就是要的,如果都不是,那就判断选中的这一个元素和上一个元素那个最接近要找的,完事后记得删
AC代码
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main() {ios::sync_with_stdio(false);cin.tie(0);int m; cin>>m;while(m--) {int mod, c; cin>>mod>>c;if(mod == 1) {if(st.count(c)) cout<<"Already Exist\n";else st.insert(c);}else {if(st.empty()) {cout<<"Empty\n"; continue;}auto ans = st.lower_bound(c);if(ans == st.end()) ans = --(st.end());else if(ans == st.begin()) ans = st.begin(); // 这一行干啥的else {auto l = ans; l--;ans=(c-*l<=*ans-c?l:ans);}cout<<*ans<<"\n";st.erase(ans);}}return 0;
}