1057. Stack (30)
来源:互联网 发布:域名查询和注册 编辑:程序博客网 时间:2024/05/01 08:06
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 (<= 105). Then N lines follow, each contains a command in one of the following 3 formats:
Push keyPop
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:17PopPeekMedianPush 3PeekMedianPush 2PeekMedianPush 1PeekMedianPopPopPush 5Push 4PeekMedianPopPopPopPopSample Output:
InvalidInvalid322124453Invalid
c语言的输入输出+统计方法求中位数+树状数组+二分搜索。
#include <cstdio>#include <algorithm>using namespace std;const int maxn = 100005;int C[maxn],st[maxn];inline int lowbit(int x){return x & -x;}int sum(int x){int ret = 0;while(x > 0){ret += C[x]; x -= lowbit(x);}return ret;}int add(int x,int d){while(x <= maxn){C[x] += d; x += lowbit(x);}}int lower_bound(int x){int mid,low=0,high = maxn - 1;while(low < high){int mid = low + (high - low)/2;if(sum(mid) >= x)high = mid;else low = mid + 1;}return low;}int main(){int n,top = -1;scanf("%d",&n);char cmd[20];for(int i=0;i<n;i++){scanf("%s",cmd);if(cmd[1] == 'o'){if(top == -1)printf("Invalid\n");else {int t = st[top--];printf("%d\n",t);add(t,-1);}}else if(cmd[1] == 'u'){int a;scanf("%d",&a);add(a,1);st[++top] = a;}else if(cmd[1] == 'e'){int sz = top + 1;if(sz == 0)printf("Invalid\n");else if(sz % 2 == 0){printf("%d\n",lower_bound(sz/2));}else {printf("%d\n",lower_bound((sz+1)/2));}}}return 0;}
- 1057. Stack (30)-PAT
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- pat 1057. Stack (30)
- 1057. Stack (30)--看
- 1057. Stack (30)
- PAT 1057. Stack (30)
- 1057. Stack (30)
- 【PAT】1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 1057. Stack (30)
- 一个tomcat配置多个端口
- git submodule常用的几个命令
- Android 微信摇骰子
- spring定时器
- 新人报道
- 1057. Stack (30)
- Info.plist Utility Error: “Info.plist couldn't be opened because there is no such file”
- 新网某处设计缺陷可任意用户密码重置及手机号密码密文泄漏(大众点评网为例)
- 切除边缘
- Matlab学习01-Mupad画图
- JAVA 写Excel附件 每天定时发送邮件
- 如何正确的获得一个view的宽和高
- eclipse下C语言环境的配置
- [学习笔记]MFC 中的CDC类