借鉴文章:
用vector实现普通平衡树!_致上-CSDN博客_vector平衡树
您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作:
1.插入数值 x
2.删除数值 x (若有多个相同的数,应只删除一个)。
3.查询数值 x 的排名(若有多个相同的数,应输出最小的排名)。
4.查询排名为 x 的数值。
5.求数值 x 的前驱(前驱定义为小于 x 的最大的数)。
6.求数值 x 的后继(后继定义为大于 x 的最小的数)。
-
注意: 数据保证查询的结果一定存在。
输入格式
-
第一行为 n,表示操作的个数。
-
接下来 n 行每行有两个数 opt 和 x,opt 表示操作的序号(1≤opt≤6 )。
输出格式
对于操作 3,4,5,6 每行输出一个数,表示对应答案。
数据范围
1≤n≤100000,所有数均在 ?107 到 107 内。
输入样例:
8 1 10 1 20 1 30 3 20 4 2 2 10 5 25 6 -1
输出样例:
2 20 20 20
初学平衡树也是被y总的模板搞得头昏脑胀,又是左旋又是右旋,最后再视频评论区看到了用vector来解决平衡树的问题。虽然不是特理解,先记住模板吧。
借鉴的文章放在最开头的地方了,感兴趣的可以去看看。
#include<bits/stdc++.h>
using namespace std;int n,opt,x;vector<int> epic;int main()
{ios::sync_with_stdio(0);cin>>n;while(n--){cin>>opt>>x;if(opt==1) epic.insert(upper_bound(epic.begin(),epic.end(),x),x);else if(opt==2) epic.erase(lower_bound(epic.begin(),epic.end(),x));else if(opt==3) printf("%d\n",lower_bound(epic.begin(),epic.end(),x)-epic.begin()+1);else if(opt==4) printf("%d\n",epic[x-1]);else if(opt==5) printf("%d\n",*--lower_bound(epic.begin(),epic.end(),x));else if(opt==6) printf("%d\n",*upper_bound(epic.begin(),epic.end(),x));}
}