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 10e5.
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
求棧中的第k大元素的時候,可以利用樹狀數組,在元素值的數值範圍上建立樹狀數組
對於二分還有一個問題:
假設某一時刻棧中元素爲: 1 2 6 7 那麼2、3、4、5進行get_sum時都是返回的2,但是3、4、5並不在棧中,因此返回3、4、5是不合理的,即需要返回大的是2
二分有兩個模板,可以處理目標有連續的多個相同值得情況,一個返回最左邊的元素,一個返回的是最右邊的元素,這裏返回的是最左邊的元素!!!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int h[100010],head = 0,tail = -1;
int c[100010];
int lowbit(int x){
return x & -x;
}
void update(int x,int d){
for (int i = x; i < 100010 ; i += lowbit(i))
c[i] += d;
}
int get_sum(int x){
int ans = 0;
for ( ; x ; x -= lowbit(x))
ans = ans + c[x];
return ans;
}
int main(){
int n,key; string op;
cin >> n;
for (int i = 0; i < n; ++i){
cin>>op;
if (op == "Push"){
cin>>key;
update(key,1);
h[++tail] = key;
}else if (op == "PeekMedian"){
if (head <= tail){
int len = tail - head + 1;
int k;
if (len & 1) // 奇數
k = (len + 1) / 2;
else // 偶數
k = len / 2;
int l = 1,r = 1e5;
while(l < r){
int mid = l + r >> 1;
if (k <= get_sum(mid))
r = mid;
else l = mid + 1;
}
cout<< l <<endl; // 此時l和r相同,因此 cout<<r<<endl; 也可以
}else
puts("Invalid");
}else{
if (head <= tail){
update(h[tail],-1);
printf("%d\n",h[tail]);
tail--;
}else{
puts("Invalid");
}
}
}
return 0;
}