1057. Stack (30)
时间限制 150 ms 内存限制 65536 kB 代码长度限制 16000 B
判题程序 Standard 作者 CHEN, Yue
Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<= 105). Then N lines follow, each contains a command in one of the following 3 formats:
Push key
Pop
PeekMedian
where key is a positive integer no more than 105.
Output Specification:
For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print “Invalid” instead.
Sample Input:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
暴力过不了啊啊啊,树状数组不会啊啊啊
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <stack>
#include <cstring>
#include <string>
using namespace std;
const int MaxN = 100010;
const int Sqrt = 310;
struct st {
stack<int> St;
int blocks[Sqrt];
int table[MaxN];
bool pop(int &res) {
if (St.empty())return false;
res = St.top();
St.pop();
--table[res];
--blocks[res / Sqrt];
return true;
}
bool push(int val) {
St.push(val);
++table[val];
++blocks[val / Sqrt];
return true;
}
bool PeekMedian(int &res) {
if (St.empty())return false;
int sum = 0, num = 0, idx = 0;
int N = (St.size() % 2) ? ((St.size() + 1) / 2) : (St.size() / 2);
while (sum + blocks[idx] < N) sum += blocks[idx++];
num = idx * Sqrt;
while (sum + table[num] < N)sum += table[num++];
res = num;
return true;
}
}Stack;
int main() {
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
int key, res;
bool flag;
char ins[30];
int n; scanf("%d",&n);
while (n--) {
scanf("%s", ins);
if (strcmp(ins, "Pop") == 0) flag = Stack.pop(res);
else if (strcmp(ins, "PeekMedian") == 0) flag = Stack.PeekMedian(res);
else if (strcmp(ins, "Push") == 0) {
scanf("%d", &key);
Stack.push(key);
continue;
}
flag ? (printf("%d\n",res)) : (printf("Invalid\n"));
}
return 0;
}