一、题意介绍
初始为空的数字集合,需支持 种操作:查询 的排名(小于 的数的个数 +1)、查询排名为 的元素、查询 的前驱(小于 的最大数,不存在输出 )、查询 的后继(大于 的最小数,不存在输出 )、插入未出现过的新数,总操作数不超过 。
二、核心思路
算法:基于有序集合的二分定位实现全操作,无需手写平衡树,利用内置二分接口快速定位目标位置,整体时间复杂度 ,完全适配数据规模。
数据结构:使用 STL 中的set<int>,自动维护元素全局升序,天然去重,自带lower_bound/upper_bound二分查找接口,省去手动维护有序序列的成本。
三、过程分析
开启ios::sync_with_stdio(0)输入输出优化,提升 次操作的运行效率。
逐操作分支处理:
- 操作1:用
lower_bound(x)找到首个 的迭代器,计算从集合首到该迭代器的元素数 +1,即为 的排名。 - 操作2:将首迭代器向后移动 步,指向元素就是排名为x的数。
- 操作3:用
lower_bound(x)定位,若迭代器是集合首则无前驱,否则取迭代器前一位元素作为前驱。 - 操作4:用
upper_bound(x)定位,若迭代器是集合尾则无后继,否则取该位置元素作为后继。 - 操作5:直接调用
insert(x)插入新数,自动完成有序维护。
四、代码
#include<bits/stdc++.h>
using namespace std;
set<int>s;
int main(){
ios::sync_with_stdio(0),cin.tie(0);
int q,op,x;
cin>>q;
while(q--){
cin>>op>>x;
if(op==1){
auto it=s.lower_bound(x);
cout<<distance(s.begin(),it)+1<<'\n';
}
else if(op==2){
auto it=s.begin();
advance(it,x-1);
cout<<*it<<'\n';
}
else if(op==3){
auto it=s.lower_bound(x);
cout<<(it==s.begin()?-2147483647:*prev(it))<<'\n';
}
else if(op==4){
auto it=s.upper_bound(x);
cout<<(it==s.end()?2147483647:*it)<<'\n';
}
else s.insert(x);
}
return 0;
}求关QwQ