L3-002 特殊堆栈 (30 分) vector的妙用

题目链接

在这里插入图片描述
可以用一个vector来维持我们栈中元素的有序性,对于入栈操作,我们二分找到新入栈元素应该在的位置,然后插入进vector中;对于出栈操作,我们同样可以二分找到当前栈顶元素所在位置,然后将其从vector中删除;求中位数的操作在一个已经排好序的vector中可以很容易找到。

  • 通过迭代器对vector进行erase和insert操作都是一个摊销常数级别的复杂度。
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;

const int N = 1e3 + 10;
const ll INF = 1e15;
const int mod = 1e9 + 7;

int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    // #ifndef ONLINE_JUDGE
    //     freopen("1.in", "r", stdin);
    //     freopen("1.out", "w", stdout);
    // #endif
    int key;
    cin >> key;
    stack<int> S;
    vector<int> ans;
    while(key --) {
        string op;
        cin >> op;
        if(op == "Pop") {
            if(S.size() == 0) cout << "Invalid" << endl;
            else {
                int tem = S.top();
                cout << tem << endl;
                auto it = lower_bound(ans.begin(), ans.end(), tem);
                ans.erase(it);
                S.pop();
            }
        }
        if(op == "PeekMedian") {
            if(S.size() == 0) cout << "Invalid" << endl;
            else {
                if(ans.size() & 1) cout << ans[(S.size() + 1) / 2 - 1] << endl;
                else  cout << ans[S.size() / 2 - 1] << endl;
            }
        }
        if(op == "Push") {
            int x;
            cin >> x;
            auto it = upper_bound(ans.begin(), ans.end(), x);
            ans.insert(it, x);
            S.push(x);
        }
    }
    return 0;
}
/*
*/ 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值