即维护一个有序VECTOR和LOWER_BOUND和UPPER_BOUND的简单应用。在1E5的数据规模下,每次最高Log n的复杂度,很自然想到二分。
#include <bits/stdc++.h>
using namespace std;
int main(){
int stack_cnt = 0, n;
cin >> n;
string str;
stack<int> Stack;
vector<int> ve;
for(int i = 0; i < n; ++i){
cin >> str;
if(str == "Push"){
int val;
cin >> val;
stack_cnt++;
Stack.push(val);
ve.insert(upper_bound(ve.begin(), ve.end(), val), val);
}
else if(str == "Pop"){
if(0 == stack_cnt){
cout << "Invalid" << endl;
continue;
}
stack_cnt--;
int val = Stack.top();
cout << val << endl;
Stack.pop();
ve.erase(lower_bound(ve.begin(), ve.end(), val));
}
else if(str == "PeekMedian"){
if(0 == stack_cnt){
cout << "Invalid" << endl;
continue;
}
if(stack_cnt % 2 == 1) cout << ve[(stack_cnt + 1) / 2 - 1] << endl;
else cout << ve[stack_cnt / 2 - 1]<< endl;
}
}
}