题目
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 N N elements, the median value is defined to be the ( N / 2 ) (N/2) (N/2)-th smallest element if N N N is even, or ( ( N + 1 ) / 2 ) ((N+1)/2) ((N+1)/2)-th if N N N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N ( ≤ 1 0 5 ) N(\le10^5) N(≤105). Then N N 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
1
0
5
10^5
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
题目大意
模拟栈操作,与栈的不同之处在于能够求栈中元素的中位数,看似简单的题目,实则很难,个人觉得。
思路
如果采用常规方法就是对元素排序,再取中位数,但是对这题而言显然会超时,那么有什么好的方法求取中位数呢?
这里用到了树状数组的变形,关于树状数组,可查阅我的博客:
我们可以将求前缀和变为求前缀的个数,具体做法就是,更新单节点时,我们不直接插入节点值,而是加一,代表这个数出现一次,这样计算出来的前缀和就是前缀的个数。具体看代码中的讲解。
代码
#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
const int maxn = 100001;
int c[maxn], n;
stack<int> sta;
int lowbit(int m){
return m & (-m);
}
int getSum(int m){
int cnt = 0;
while(m > 0){
cnt += c[m]; // c[m]中记录的信息表示m出现的次数
m -= lowbit(m);
}
return cnt;
}
void update(int x, int v){
while(x <= maxn){
c[x] += v; // c[x]只有加减1的操作
x += lowbit(x);
}
}
int peekMedian(){
int left = 1, mid, right = maxn, k = (sta.size()+1)/2;
while(left < right){
mid = (left + right)/2;
if(getSum(mid) >= k) // 此时getSum(mid)代表<=mid的元素个数
right = mid;
else
left = mid + 1;
}
return left;
}
int main(){
string op;
fill(c, c+maxn, 0);
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%s", &op[0]);
if(op[1] == 'o'){
if(sta.empty())
printf("Invalid\n");
else{
printf("%d\n", sta.top());
update(sta.top(), -1); // 将t出现过这个记录删除
sta.pop();
}
}
else if(op[1] == 'e'){
if(sta.empty())
printf("Invalid\n");
else
printf("%d\n", peekMedian());
}
else{
int t;
scanf("%d", &t);
sta.push(t);
update(t, 1); // 不插入t,只记录t出现过
}
}
return 0;
}