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 Nis 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 Nlines follow, each contains a command in one of the following 3 formats:
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.
知识点:树状数组,二分查找
二分查找的写法
对比两种写法:
正确:
find(x){ while(l!=r){ mid=(l+r)/2; if(list[mid]>=x){ r=mid; }else{ l=mid+1; } } }
错误:
find(x){ while(l!=r){ mid=(l+r)/2; if(list[mid]>x){ r=mid-1; }else{ l=mid; } } }
1 #include <iostream> 2 #include <stack> 3 using namespace std; 4 const int maxn = 100005; 5 6 int n; 7 int c[maxn]; 8 stack<int> st; 9 10 int lowbit(int v){ // lowbit()函数取二进制数最后一个1 11 return v&(-v); 12 } 13 14 15 int getSum(int x){ // 往前加和 16 int sum=0; 17 for(int i=x;i>0;i-=lowbit(i)){ 18 sum += c[i]; 19 } 20 return sum; 21 } 22 23 void upDate(int v,int p){ // 往后更新 24 for(int i=v;i<maxn;i+=lowbit(i)){ 25 c[i]+=p; 26 } 27 } 28 29 int findMid(){ 30 printf(" "); 31 int mid=(st.size()+1)/2; 32 int l=1, r=maxn-1; 33 int cnt=0; 34 while(l!=r&cnt<100){ // 二分查找 35 cnt++; 36 printf("* %d %d ",l,r); 37 int m=(l+r)/2; 38 if(getSum(m)>=mid){ 39 r=m; 40 }else{ 41 l=m+1; 42 } 43 } 44 return l; 45 } 46 47 int main(int argc, char *argv[]) { 48 fill(c,c+maxn,0); 49 50 scanf("%d",&n); 51 char cmd[15]; int key; 52 for(int i=0;i<n;i++){ 53 scanf("%s",cmd); 54 if(cmd[1]=='u'){ 55 scanf("%d",&key); 56 57 st.push(key); 58 upDate(key,1); 59 }else if(cmd[1]=='o'){ 60 if(st.size()==0) printf("Invalid "); 61 else{ 62 upDate(st.top(),-1); 63 printf("%d ",st.top()); 64 st.pop(); 65 } 66 }else if(cmd[1]=='e'){ 67 if(st.size()==0) printf("Invalid "); 68 else{ 69 printf("%d ",findMid()); 70 }; 71 } 72 } 73 }
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