题解:
题目就是求第k小元素问题。由于操作次数比较多,因此直接排序输出中间元素会超时,因此这题要用到第K小元素的经典做法之一,树状数组。用树状数组来维护现在栈内元素的信息,然后使用二分查找中间元素的值。这样时间复杂度是
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)。
实现细节见代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
int c[MAXN];
stack<int> all;
int lowbit(int x) {
return x & -x;
}
void add(int x, int v) {
for (int i = x; i < MAXN; i += lowbit(i)) {
c[i] += v;
}
}
int getsum(int x) {
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i)) {
sum += c[i];
}
return sum;
}
void get() {
int l = 1, r = MAXN, k = (all.size() + 1) / 2;
while (l < r) { // 二分找第K小元素
int mid = l + r >> 1;
if (getsum(mid) >= k) {
r = mid;
}
else {
l = mid + 1;
}
}
cout << l << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
while (n--) {
string op;
cin >> op;
if (op[1] == 'u') {
int x;
cin >> x;
all.push(x);
add(x, 1);
}
else if (op[1] == 'o') {
if (!all.empty()) {
cout << all.top() << endl;
add(all.top(), -1);
all.pop();
}
else {
cout << "Invalid" << endl;
}
}
else {
if (!all.empty()) {
get();
}
else {
cout << "Invalid" << endl;
}
}
}
return 0;
}