题目链接
题目大意
模拟一个栈的push和pop操作,且在输入PeekMedian时输出栈里所有数的中位数。
解题思路
使用c++的内置库stack和pb_ds可快速解决,无需手写高级数据结构或者手动二分(懒)。使用了自带的红黑树中的find_by_order查找第k大的元素,实现中位数查找,由于此处不支持mulity-set,所以不能有重复元素,需要用map定义一个偏移量,具体看代码就可以了。
代码
#include<ext/pb_ds/assoc_container.hpp>
#include<bits/stdc++.h>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef tree<ll ,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> Stree;
Stree Tree;
map<int , int> mp;
ll n,k;
string s;
stack<int> sk1;
int main()
{
cin>>n;
while(n--){
cin>>s;
if(s=="Pop")
{
if(sk1.size()==0)
cout<<"Invalid\n";
else{
k=sk1.top();
Tree.erase(Tree.find((k<<20)+(--mp[k])));
sk1.pop();
cout<<k<<endl;
}
}
else if(s=="PeekMedian"){
if(sk1.size()==0) cout<<"Invalid\n";
else
cout<<((*Tree.find_by_order((sk1.size()+1)/2-1))>>20)<<endl;;
}
else {
cin>>k;
sk1.push(k);
Tree.insert((k<<20)+mp[k]++);
}
}
return 0;
}