题目链接
可以用一个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;
}
/*
*/