1057 Stack (30 分)
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
#include<iostream>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<cmath>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<stdio.h>
#include<cstring>
#include<string.h>
#include <cstdio>
#include<map>
#include<set>
#define INF 10010
//#include<bits/stdc++.h>
using namespace std;
int mid = 10005;
multiset<int>s1, s2;
void adjust() {
multiset<int>::iterator it;
if (s1.size() < s2.size()) {
it = s2.begin(); //s2大于mid,begin()是小顶
s1.insert(*it);
s2.erase(it);
}
else if (s1.size() > s2.size() + 1) {
it = s1.end(); //s1小于等于mid,end()是大顶
it--;
s2.insert(*it);
s1.erase(it);
}
if (!s1.empty()) {
it = s1.end();
it--;
mid = *it;
}
}
stack<int>sta;
int tp, v;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
char temp[100];
scanf("%s", temp);
if (strcmp(temp, "Pop") == 0) {
if (sta.size() == 0) printf("Invalid\n");
else {
tp = sta.top();
printf("%d\n", tp);
sta.pop();
if (tp <= mid) s1.erase(s1.find(tp));
else s2.erase(s2.find(tp));
adjust();
}
}
else if (strcmp(temp, "Push") == 0) {
scanf("%d", &v);
sta.push(v);
if (v <= mid)s1.insert(v);
else s2.insert(v);
adjust();
}
else if (strcmp(temp, "PeekMedian") == 0) {
if (sta.size() == 0)printf("Invalid\n");
else printf("%d\n", mid);
}
}
return 0;
}