1057. Stack (30)

来源:互联网 发布:淘宝我的小蜜是客服么 编辑:程序博客网 时间:2024/05/18 01:36

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 key
Pop
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 4PeekMedianPopPopPopPop
Sample Output:
InvalidInvalid322124453Invalid
这题重复排序超时三个点

用树状数组。

函数void updata(int x,int v)  是将第x个数加上v

函数int getsum(int x) 返回前x个整数合

输入一个数x,将第x个数加1

要查找中位数时,二分求前x项合,找到中位数输出

#include<iostream>  #include<cstring>  #include<cstdio>  #include<queue>  #include<stack>  #include<algorithm>  #include<vector> #include<map>#define lowbit(i) (i&(-i))#define maxn 100001using namespace std;int t[100001]={0};void updata(int x,int v){while(x<maxn){t[x]+=v;x+=lowbit(x);}}int getsum(int x){int sum=0;while(x){sum+=t[x];x-=lowbit(x);}return sum;}int main(){int n;cin>>n;stack<int> s;for(int i=0;i<n;i++){char fz[10];scanf("%s",fz);if(fz[1]=='o'){if(s.size()==0) printf("Invalid\n");else {updata(s.top(),-1);printf("%d\n",s.top());s.pop();}}else if(fz[1]=='u'){int num;scanf("%d",&num);updata(num,1);s.push(num);}else{if(s.size()==0) {printf("Invalid\n");continue;}int k=(s.size()+1)/2;int zuo=1,you=maxn,mid;while(zuo<you){mid=(zuo+you)/2;if(getsum(mid)>=k){you=mid;}else{zuo=mid+1;}}printf("%d\n",you);}}return 0;}


https://www.liuchuo.net/archives/2268


针对树状数组做的一些笔记