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 Nelements, 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<vector>
#include<algorithm>
#include<set>
using namespace std;
multiset<int> set_l;
multiset<int> set_r;
int out_mid(){
multiset<int>::iterator it;
if(set_l.size() < set_r.size()){
it = set_r.begin();
set_r.erase(it);
set_l.insert(*it);
}
if(set_l.size() > set_r.size() + 1){
it = set_l.end();
--it;
set_l.erase(it);
set_r.insert(*it);
}
int mid = 0;
if(!set_l.empty()){
it = set_l.end();
--it;
mid = *it;
}
return mid;
}
int main(){
int n;
int mid;
cin >> n;
stack<int> st;
for(int i = 0; i < n; i++){
string s;
cin >> s;
if(s == "Push"){
int data;
scanf("%d", &data);
st.push(data);
if(set_l.empty()){
set_l.insert(data);
}else if(data <= mid)
{
set_l.insert(data);
}else
{
set_r.insert(data);
}
mid = out_mid();
}else
{
if(st.empty()){
printf("Invalid\n");
}else
{
if(s == "Pop"){
printf("%d\n", st.top());
if(st.top() <= mid)
{
set_l.erase(set_l.find(st.top()));
}else
{
set_r.erase(set_r.find(st.top()));
}
st.pop();
mid = out_mid();
}else
{
printf("%d\n", mid);
}
}
}
}
return 0;
}
本文介绍了一种特殊的数据结构——栈,该栈除了基本的Push和Pop操作外,还支持PeekMedian操作,即返回当前栈中所有元素的中位数。通过使用两个multiset来维护数据,确保在进行插入和删除操作时能够高效地更新中位数。
2383

被折叠的 条评论
为什么被折叠?



