题目链接
考察二分,这里用了lower_bound函数
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
vector<int> a;//用a来模拟栈
vector<int> b;//b保存的是有序的数据
int main(int argc, char const *argv[]) {
int t;
vector<int>::iterator it;
cin >> t;
while (t--) {
string s;
cin >> s;
if (s == "Pop") {
if (a.size() == 0)
printf("Invalid\n");
else {
it = lower_bound(b.begin(), b.end(), a[a.size() - 1]);//找到栈最后一个元素的地址
b.erase(it);//在b中删掉它
printf("%d\n", a[a.size() - 1]);
a.pop_back();//在a中删掉,意味着栈弹出这个元素
}
} else if (s == "Push") {
int x;
cin >> x;
a.push_back(x);
it = lower_bound(b.begin(), b.end(), x);
b.insert(it, x);//在b中插入,维护b有序的方法是,插入有序
} else if (s == "PeekMedian") {
if (a.size() == 0)
printf("Invalid\n");
else {
if (a.size() % 2 == 0)
printf("%d\n", b[a.size() / 2 - 1]);
else
printf("%d\n", b[a.size() / 2]);
}
}
}
return 0;
}