您的位置:首页 > 编程语言 > C语言/C++

1057. Stack (30)

2016-03-20 13:04 483 查看
    用直方图的方式来动态维护中位数

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ PAT Stack