题目描述
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.
输入描述:
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.
输出描述:
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.
输入例子:
17 Pop PeekMedian Push 3 PeekMedian Push 2 PeekMedian Push 1 PeekMedian Pop Pop Push 5 Push 4 PeekMedian Pop Pop Pop Pop
输出例子:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
multiset和set一样,都是自动以升序将插入元素进行排序。
与set不同的是,multiset不去重。
设一个中值变量mid,Push时,如果数小于等于中值,插入s1(multiset)数组,否则插入s2(multiset)数组。
每次Pop或Push后,需保持s1数组与s2数组元素基本相等(若s1.size()<s2.size(),将s2数组的第一个元素给s1。若s1.size()>s.size()+1,将s1数组的最后一个元素给s2)。并且,若s1数组非空,则将中值mid更新为s1数组的最后一个元素。
我的代码:
#include<iostream>
#include<set>
#include<string.h>
#include<stack>
using namespace std;
multiset<int>s1,s2;
int n,m,mid=999999;
void midst()
{
multiset<int>::iterator it;
if(s1.size()<s2.size())
{
it=s2.begin();
s1.insert(*it);
s2.erase(it);
}
if(s1.size()>s2.size()+1)
{
it=s1.end();
it--;
s2.insert(*it);
s1.erase(it);
}
if(!s1.empty())
{
it=s1.end();
it--;
mid=*it;
}
}
int main()
{
stack<int>s;
char x[20];
scanf("%d%*c",&n);
while(n--)
{
scanf("%s",x);
if(strcmp(x,"Pop")==0)
{
if(s.empty()) puts("Invalid");
else
{
int t=s.top();
printf("%d\n",t);
s.pop();
if(t<=mid) s1.erase(s1.find(t));
else s2.erase(s2.find(t));
midst();
}
}
else if(strcmp(x,"PeekMedian")==0)
{
if(s.empty()) puts("Invalid");
else printf("%d\n",mid);
}
else if(strcmp(x,"Push")==0)
{
scanf("%d%*c",&m);
s.push(m);
if(m<=mid) s1.insert(m);
else s2.insert(m);
midst();
}
}
return 0;
}