题目
1057 Stack (30)(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 (<= 10^5^). 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 10^5^.
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:
|
|
Sample Output:
|
|
想法
最傻的办法,就用一个数组,当栈维护
要找中位数的时候,复制一份sort一下
这样肯定是会超时的
怎么维护这个大小信息呢?是个关键
两个信息需要维护,一个是顺序信息,一个是大小信息
顺序信息用位置来表示,那么大小信息呢?开个链表来存吗?不是很合理。
参考了这位:https://blog.csdn.net/frozenshore/article/details/47836935 的解法,可以用set,set自带排序
维护两个set,A和B,保证A中元素都小于等于B,且A.size() == B.size() || A.size() - 1 == B.size()
push或pop之后,要更新这两个set来保持正确性
学习了,学习了!
答案
|
|
用了multi_set
总结
借用STL中的东西来方便自己,尽管是大材小用。
set自带排序,也可以自己指定Compare
方法。
顺便复习下set的使用方法:
|
|