本文共 2193 字,大约阅读时间需要 7 分钟。
初始状态下,系统中没有任何数字。系统需要处理三种操作:添加、删除和查询。具体规则如下:
操作1:add x
添加数字x到系统中。如果系统中已经存在一个与x相差小于等于k的数字,则忽略这次添加操作。操作2:del x
删除数字x。如果系统中存在多个与x相差小于等于k的数字,则全部删除。如果没有数字x,忽略该操作。操作3:query x
判断是否存在一个数字与x相差小于等于k。数据结构选择
使用标准库set
来存储数字。set
数据结构可以自动排序,并支持快速查找和插入操作,非常适合这种基于范围查询的场景。实现细节
性能优化
使用set
的lower_bound
方法可以快速找到插入位置,确保操作的时间复杂度为O(log n)。这种方法在处理大量操作时表现优异。#include#include using namespace std;set aa;int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int m, k; cin >> m >> k; string str; for (int i = 0; i < m; ++i) { cin >> str; if (str[0] == 'a') { int x; cin >> x; if (!aa.empty()) { auto iter = aa.lower_bound(x - k); if (iter != aa.end() && *iter > x + k) { aa.insert(x); } } else { aa.insert(x); } } else if (str[0] == 'd') { int x; cin >> x; auto iter = aa.lower_bound(x - k); set bb; while (iter != aa.end() && *iter <= x + k) { bb.push_back(*iter); ++iter; } while (!bb.empty()) { aa.erase(bb.top()); bb.pop(); } } else { int x; cin >> x; if (aa.empty()) { cout << "No" << endl; continue; } auto iter = aa.lower_bound(x - k); if (iter != aa.end() && *iter > x + k) { cout << "Yes" << endl; } else { cout << "No" << endl; } } }}
数据结构
使用set<int> aa;
来存储系统中的所有数字。set
的优势在于自动排序和快速查找。输入处理
使用ios::sync_with_stdio(false);
和cin.tie(0);
来提高输入输出效率,避免超时。操作处理
lower_bound
找到插入位置。lower_bound
查找范围,判断是否存在符合条件的数字。异常处理
对于del x
操作,若没有找到x,则直接忽略。对于query x
,若系统为空则直接返回"No"。通过使用set
数据结构和lower_bound
方法,可以高效地实现操作的逻辑,确保每个操作的时间复杂度为O(log n)。这种方法不仅简洁高效,还能在大规模数据下表现稳定。
转载地址:http://oyhlz.baihongyu.com/