模拟stack的push和pop,并能实时查询中位数。代码是算法笔记中的代码,可作为分块思想和树状数组的模板参考。
分块思想
#include<cstdio>
#include<stack>
#include<cstring>
using namespace std;
const int maxn=100010;
const int sqrN=316;
stack<int>st;
int block[sqrN];//表示第i块中存在的元素个数
int table[maxn];//表示整数x的当前存在个数
void peekMedian(int K){
int sum=0;
int idx=0;//块号
while(sum+block[idx]<K){
sum+=block[idx++];
}
int num=idx*sqrN;
while(sum+table[num]<K){
sum+=table[num++];
}
printf("%d\n",num);
}
void push(int x){
st.push(x);
block[x/sqrN]++;
table[x]++;
}
void pop(){
int x=st.top();
st.pop();
block[x/sqrN]--;
table[x]--;
printf("%d\n",x);
}
int main(){
int x,query;
memset(block,0,sizeof(block));
memset(table,0,sizeof(table));
char cmd[20];
scanf("%d",&query);
for(int i=0;i<query;i++){
scanf("%s",cmd);
if(strcmp(cmd,"Push")==0){
scanf("%d",&x);
push(x);
}else if(strcmp(cmd,"Pop")==0){
if(st.empty()==true){
printf("Invalid\n");
}else{
pop();
}
}else{
if(st.empty()==true){
printf("Invalid\n");
}else{
int K=st.size();
if(K%2==1)
K=(K+1)/2;
else
K=K/2;
peekMedian(K);
}
}
}
return 0;
}
树状数组
#include <iostream>
#include <stack>
#define lowbit(i) ((i) & (-i))
const int maxn = 100010;
using namespace std;
int c[maxn];
stack<int> s;
void update(int x, int v) {//存储有几个x
for(int i = x; i < maxn; i += lowbit(i))
c[i] += v;
}
int getsum(int x) {//求比x小的数有几个
int sum = 0;
for(int i = x; i >= 1; i -= lowbit(i))
sum += c[i];
return sum;
}
void PeekMedian() {//二分法
int left = 1, right = maxn, mid, k = (s.size() + 1) / 2;
while(left < right) {
mid = (left + right) / 2;
if(getsum(mid) >= k)
right = mid;
else
left = mid + 1;
}
printf("%d\n", left);
}
int main() {
int n, temp;
scanf("%d", &n);
char str[15];
for(int i = 0; i < n; i++) {
scanf("%s", str);
if(str[1] == 'u') {
scanf("%d", &temp);
s.push(temp);
update(temp, 1);
} else if(str[1] == 'o') {
if(!s.empty()) {
update(s.top(), -1);
printf("%d\n", s.top());
s.pop();
} else {
printf("Invalid\n");
}
} else {
if(!s.empty())
PeekMedian();
else
printf("Invalid\n");
}
}
return 0;
}