用set保存,set有内部默认从小到大排序的特性还有自动去重的特性。
在进行检测的时候使用set的lower_bound函数,这个函数对找到最近的插入位置,如果存在该数就返回第一个数的下标。如果不存在就返回第一个大于该数的下标,所以是否有符合要求的数只需要看返回的迭代器对应的数以及前一个数是否符合范围要求,如果他两都不符合那么就不可能有符合要求的数了。
//用set保存,set有内部默认从小到大排序的特性还有自动去重的特性。
#include <bits/stdc++.h>
using namespace std;
int rd() {
int num=0, k = 1;
char ch = getchar();
while (!((ch == '-')||(ch>='0'&&ch<='9'))) {
ch = getchar();
}
while (ch == '-') {
k = k^1;
ch = getchar();
}
while (ch>='0'&&ch<='9') {
num = num*10+(ch-'0');
ch = getchar();
}
return num;
}
vector<set<int>::iterator> dst;
set<int> st;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int m, k;
cin>>m>>k;
// m = rd();k = rd();
st.insert(100000000);
st.insert(-100000000);
string s;
int x;
while (m--) {
cin>>s;
cin>>x;
// x = rd();
if (s=="add") {
set<int>::iterator it = st.lower_bound(x);
if (abs(*it-x)<=k) continue;
it--;
if (abs(*it-x)<=k) continue;
st.insert(x);
}
if (s=="query") {
set<int>::iterator it = st.lower_bound(x);
if (abs(*it-x)<=k) {
cout<<"Yes"<<endl;
continue;
}
it--;
if (abs(*it-x)<=k) {
cout<<"Yes"<<endl;
continue;
}
cout<<"No"<<endl;
}
int n = 0;
if (!st.empty()&&s=="del") {
set<int>::iterator it;
for(it = st.lower_bound(x - k);it != st.end();){
if(*it - x > k){
break;
}
int y = *it;
//对于节点式容器,删除节点前对节点进行后移的操作,因为其他元素不会失效
it ++ ;
st.erase(y);
}
}
}
return 0;
}

京公网安备 11010502036488号