PTA 甲级 1057 Stack

题目链接

1.使用两个multiset维护中值,up和down分别存储一半的数据。

2.multiset允许元素重复,set元素不重复。

两者默认升序排列,降序使用multiset<int, greater<int>>set1;

3.常用函数:

insert(int x)

find(int x) 返回迭代器

earse(iterator it)

lower_bound(int x) 返回第一个>=x的迭代器

upper_bound

size

#include<bits/stdc++.h>

using namespace std;
stack<int> st;
multiset<int> up,down;
void ba(){
    while(up.size()>down.size()){
        down.insert(*up.begin());
        up.erase(up.begin());
    }
    while(down.size()>up.size()+1){
        auto it=down.end();it--;
        up.insert(*it);
        down.erase(it);
    }
}
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        string op;int num;
        cin>>op;
        if(op=="Push"){
            cin>>num;
            st.push(num);
            //判断
            if(up.empty()||*up.begin()>num) down.insert(num);
            else up.insert(num);
            ba();
        }
        else if(op=="Pop"){
            if(st.empty())cout<<"Invalid\n";
            else{
                int x=st.top();
                auto it=down.end();it--;//up可能为空
                if(*it < x ){
                    up.erase(up.find(x));
                }
                else  down.erase(down.find(x));
                ba();
                cout<<st.top()<<endl;
                st.pop();
            }
        }
        else{
            if(st.empty())cout<<"Invalid\n";
            else{
                auto it=down.end();it--;
                cout<<*it<<endl;
            }
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值