-
热度指数:5449
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 64M,其他语言128M
-
算法知识视频讲解
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.
示例1
输入
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
1.树状数组+二分查找
树状数组(Binary Indexed Tree(BIT))是一种能高效查找前缀和的数据结构,
具体实现原理见鄙人还没写好的拙作《树状数组的复习》。使用树状数组是为了能进行二分查找,原先遍历Count数组,最多的时候能遍历10^5次,运 用二分查找可以将查找次数优化为lg(10^5)/lg(2) < 15下面是代码
2.分桶法(分治,分层HASH,平方分割)本人快乐
的原创
最后我想说的就是,
1. 这个方法和树状数组 + 二分的方法并无矛盾,你同样可以用树状数组优化大桶元素的前缀和。
2. 还有就是如果你乐意你完全可以多分几个层玩 , 比如 key 放在 bucket[...][...][...], 分层分多了以后,你会发现这个桶变成了一棵树,如果你分层的依据是二分法,你还会发现,你分出了一棵线段树。
3. 如果数据范围增大,你可以修改 hash 使其映射到更小的空间,同时将每个大桶改为 vector<int> 数组,查询是对每个 vector<int> 中的元素排序,个人感觉不会很慢
3.线段树(分治)有种杀鸡用牛刀的感觉
3.Prioriry Queue On Multiset(红黑树是支持插入与删除的堆)真正的牛刀
废话,能随意删除某个元素还叫堆吗)。。是时候启动最终形态了,优先级队列超进化,红黑优先级队列。以上文字过于中二,请谨慎阅读。