用直方图的方式来动态维护中位数
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_INTEGER 100005
int hist[MAX_INTEGER];
inline int medianPostion(int n){
return n % 2 ? (n + 1) / 2 : n / 2;
}
int main(){
int n;
scanf("%d", &n);
vector<int> s;
fill_n(hist, MAX_INTEGER, 0);
int median = 0, count = 0;
for(int i = 0; i < n; ++i){
char cmd[15];
scanf("%s", cmd);
if(strcmp(cmd, "Push") == 0){
int num;
scanf("%d", &num);
s.push_back(num);
++hist[num];
// the number is greater than the current median
if(median < num){
if(count < medianPostion(s.size())){
while(hist[++median] == 0) ;
count += hist[median];
}
}else{
++count;
if(count - hist[median] >= medianPostion(s.size())){
count -= hist[median];
while(hist[--median] == 0) ;
}
}
}else{
if(s.empty()){
printf("Invalid\n");
continue;
}
if(strcmp(cmd, "Pop") == 0){
int num = s.back();
printf("%d\n", num);
s.pop_back();
--hist[num];
// the number is greater than the current median
if(median < num){
if(count - hist[median] >= medianPostion(s.size())){
count -= hist[median];
while(hist[--median] == 0) ;
}
}else{
--count;
if(count < medianPostion(s.size())){
while(hist[++median] == 0) ;
count += hist[median];
}
}
}else{
printf("%d\n", median);
}
}
}
return 0;
}
本文介绍了一种利用直方图来动态维护数据集中位数的算法实现方法,通过解析输入命令(Push或Pop),更新直方图并计算中位数。
5573

被折叠的 条评论
为什么被折叠?



