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:
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 思路:有点类似于操作系统的分块查找功能。建立bucket将所有数字分成大组,先大组然后再查询大组里面的元素。这个方法节省了很多时间。
1 #include <iostream> 2 #include <cstdio> 3 #include <stack> 4 #include <algorithm> 5 #include <cstring> 6 using namespace std; 7 const int part=317; 8 const int MAX=100010; 9 stack<int>st; 10 int bucket[part]={ 11 0 12 }; 13 int table[MAX]={ 14 0 15 }; 16 void Peekmedian(int size) 17 { 18 //求第K个 19 if(size%2==0) 20 size/=2; 21 else 22 size=(size+1)/2; 23 int sum=0; 24 int i=0; 25 for(i=0;i<part;i++) 26 { 27 if(sum+bucket[i]<size) 28 { 29 sum+=bucket[i]; 30 } 31 else 32 { 33 break; 34 } 35 } 36 for(int j=i*part;j<(i+1)*part;j++) 37 { 38 if(sum+table[j]>=size) 39 { 40 printf("%d\n",j); 41 return ; 42 } 43 else 44 { 45 sum+=table[j]; 46 } 47 } 48 49 } 50 int main(int argc, char *argv[]) 51 { 52 int N; 53 scanf("%d",&N); 54 while(N--) 55 { 56 char str[20]; 57 scanf("%s",str); 58 if(strcmp(str,"Push")==0) 59 { 60 int data; 61 scanf("%d",&data); 62 st.push(data); 63 table[data]++; 64 bucket[data/part]++; 65 } 66 else if(strcmp(str,"Pop")==0) 67 { 68 if(st.empty()) 69 { 70 printf("Invalid\n"); 71 } 72 else 73 { 74 int data=st.top(); 75 st.pop(); 76 printf("%d\n",data); 77 table[data]--; 78 bucket[data/part]--; 79 } 80 } 81 else 82 { 83 if(st.empty()) 84 { 85 printf("Invalid\n"); 86 } 87 else 88 { 89 Peekmedian(st.size()); 90 } 91 } 92 } 93 return 0; 94 }