分析
由于题目规定每个元素为105以内的正整数,所以可以使用分块的思想储存数据
//
// Created by CyIce on 2021/2/24.
//
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 100010;
const int SQRTN = 316;
int Arr[MAXN] = {0}, Index[SQRTN] = {0};
stack<int> S;
int peekMedian() {
int i = -1, j, pos = 0, aim = int(S.size() + 1) / 2;
while (pos < aim) {
pos += Index[++i];
}
pos -= Index[i];
for (j = i * SQRTN; j < i * SQRTN + SQRTN; ++j) {
pos += Arr[j];
if (pos >= aim) break;
}
return j;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
char op[20];
scanf("%s", op);
if (strcmp(op, "Push") == 0) {
int num;
scanf("%d", &num);
S.push(num);
Arr[num]++;
Index[num / SQRTN]++;
} else if (strcmp(op, "Pop") == 0) {
if (S.empty()) {
printf("Invalid\n");
} else {
printf("%d\n", S.top());
Arr[S.top()]--;
Index[S.top() / SQRTN]--;
S.pop();
}
} else {
if (S.empty()) {
printf("Invalid\n");
} else {
printf("%d\n", peekMedian());
}
}
}
return 0;
}