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:

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 <cstdio>
#include <algorithm>
#include <vector>
#define MAX 100000
using namespace std; int n,d,s[MAX],tree[MAX + ],c;
char ope[];
int lowbit(int t) {
return t&-t;
}
void update(int x,int y) {
while(x <= MAX) {
tree[x] += y;
x += lowbit(x);
}
}
int getsum(int x) {
int ans = ;
while(x > ) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
void printM() {
int m = (c % ? c / + : c / );///中间个数应该是第几个数
int l = ,r = MAX,mid;
while(l < r) {
mid = (l + r) / ;
if(getsum(mid) < m)l = mid + ;
else r = mid;
}
printf("%d\n",l);
}
int main() {
scanf("%d",&n);
while(n --) {
scanf("%s",ope);
if(ope[] == 'u') {
scanf("%d",&d);
update(s[c ++] = d,);
}
else if(ope[] == 'o') {
if(!c) {
printf("Invalid\n");
}
else {
update(s[-- c],-);
printf("%d\n",s[c]);
}
}
else {
if(!c) {
printf("Invalid\n");
}
else {
printM();
}
}
}
}
个数对应中间位置的最小的。

最新文章

  1. 一步步学习javascript基础篇(7):BOM和DOM
  2. NSURLConnection学习笔记
  3. Euclid求最大公约数
  4. Android开发之通过Intent启动系统应用的协议
  5. PowerDesigner概念数据模型 CDM
  6. 【HDOJ】1423 Greatest Common Increasing Subsequence
  7. Window.open 实现导航与打开窗口,导航到一个特定链接地址,也可以打开一个新的浏览器窗体
  8. 超强1000 JQuery插件
  9. Jsunpack
  10. mysql JDBC总结
  11. Winform 界面执行耗时操作--UI卡顿假死问题
  12. WPF仿网易云音乐系列(三、播放进度条+控制按钮)
  13. 关联规则挖掘算法之Apriori算法
  14. PAT甲题题解-1035. Password (20)-水
  15. RIFF格式简介
  16. 超链接 a的小手
  17. 欲哭无泪的p-value = 0.051 | 做几次重复能得到较低的p-value
  18. WebDriverAPI(4)
  19. Angularjs中的超时处理
  20. 在华为eNSP中配置简单的DHCP

热门文章

  1. 大组合取模之:1&lt;=n&lt;=m&lt;=1e6,1&lt;=p&lt;=1e9
  2. 转载一篇将C/C++ 与lua混合使用入门讲的比较好的文章
  3. 在函数中如何获取 线程对象、线程唯一ID
  4. 我的Android进阶之旅------> Android应用升级构想和要点总结
  5. linux c编程:信号(二) alarm和pause函数
  6. PHP的依赖管理工具----composer
  7. Nodejs课堂笔记—第一课:修改Webstorm的默认主题
  8. python基础4 ----字符编码
  9. shell中替换json中指定的值
  10. php面向对象加载类