-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1057.cpp
54 lines (48 loc) · 1 KB
/
1057.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <stack>
using namespace std;
const int N = 100005;
const int M = 316;
stack<int> s;
int table[N];
int block[M];
void push(int x) {
s.push(x);
block[x / M]++;
table[x]++;
}
void pop() {
int x = s.top();
s.pop();
block[x / M]--;
table[x]--;
printf("%d\n", x);
}
void peek_median() {
int cnt = 0, idx = 0, k = (s.size() + 1) / 2;
while (cnt + block[idx] < k)
cnt += block[idx++];
int num = idx * M;
while (cnt + table[num] < k)
cnt += table[num++];
printf("%d\n", num);
}
int main() {
int n, key;
cin >> n;
while (n--) {
string op;
cin >> op;
if (op == "Push") {
cin >> key;
push(key);
} else if (op == "Pop") {
if (s.empty()) printf("Invalid\n");
else pop();
} else if (op == "PeekMedian") {
if (s.empty()) printf("Invalid\n");
else peek_median();
}
}
return 0;
}