P5076 【深基16.例7】普通二叉树(简化版)题解
一、题意介绍
初始为空的数字集合,需支持
二、核心思路
算法:基于有序集合的二分定位实现全操作,无需手写平衡树,利用内置二分接口快速定位目标位置,整体时间复杂度
数据结构:使用 STL 中的set<int>,自动维护元素全局升序,天然去重,自带lower_bound/upper_bound二分查找接口,省去手动维护有序序列的成本。
三、过程分析
开启ios::sync_with_stdio(0)输入输出优化,提升
逐操作分支处理:
- 操作1:用
lower_bound(x)找到首个≥x 的迭代器,计算从集合首到该迭代器的元素数 +1,即为x 的排名。 - 操作2:将首迭代器向后移动
x-1 步,指向元素就是排名为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