Running Median
Time Limit: 1000MS
Memory Limit: 65536K
Description
For this problem, you will write a program that reads in a sequence of 32-bit signed integers. After each odd-indexed value is read, output the median (middle value) of the elements received so far.
Input
The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. The first line of each data set contains the data set number, followed by a space, followed by an odd decimal integer M, (1 ≤ M ≤ 9999), giving the total number of signed integers to be processed. The remaining line(s) in the dataset consists of the values, 10 per line, separated by a single space. The last line in the dataset may contain less than 10 values.
Output
For each data set the first line of output contains the data set number, a single space and the number of medians output (which should be one-half the number of input values plus one). The output medians will be on the following lines, 10 per line separated by a single space. The last line may have less than 10 elements, but at least 1 element. There should be no blank lines in the output.
Sample Input
3
1 9
1 2 3 4 5 6 7 8 9
2 9
9 8 7 6 5 4 3 2 1
3 23
23 41 13 22 -3 24 -31 -11 -8 -7
3 5 103 211 -311 -45 -67 -73 -81 -99
-33 24 56
Sample Output
1 5
1 2 3 4 5
2 5
9 8 7 6 5
3 12
23 23 22 22 13 3 5 5 3 -3
-7 -3
Reference Code
#include <cstdio>
#include <vector>
#include <queue>
template <class T>
struct midian{
std::priority_queue<T,std::vector<T>,std::less<T> > maxpq;
std::priority_queue<T,std::vector<T>,std::greater<T> > minpq;
void push(const T& val){
if (minpq.empty()) minpq.push(val);
else if (maxpq.size()==minpq.size()){
if (val>=maxpq.top()) minpq.push(val);
else{
minpq.push(maxpq.top());
maxpq.pop();
maxpq.push(val);
}
}
else if (maxpq.size()<minpq.size()){
if (val<=minpq.top()) maxpq.push(val);
else{
maxpq.push(minpq.top());
minpq.pop();
minpq.push(val);
}
}
}
T mid(){return minpq.top();}
};
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int p;
scanf("%d",&p);
while (p--){
midian<int> M;
int n,m;
scanf("%d%d",&n,&m);
printf("%d %d\n",n,(m+1)>>1);
int cnt=0;
for (int i=1;i<=m;++i){
int t;
scanf("%d",&t);
M.push(t);
if (i&1){
printf("%d ",M.mid());
if ((++cnt)%10==0||i==m) printf("\n");
}
}
}
return 0;
}
Tips
几乎是中位数的裸题,就是输入输出有点烦人。
为了能够在连续读取数组的过程中求中位数,我们肯定是不能用排序取中间值的方法的,所以需要借助堆来优化。其实这个想法也非常朴素,就是利用两个堆,一个最大堆,用来存小于等于中位数的所有值;一个最小堆,用来存大于等于中位数的所有值。如果我们在将数存入这两个堆中的同时可以保证这两个堆的大小相差不超过一,则中位数就仅和这两个堆的top值以及它们的size相关了。如果size相等,就加起来除二返回,否则返回size较大的堆的top值(在我以上的代码中没有这样做,因为题目说了一定是奇数,所以不会出现size相同的情况)。我们可以先按规则push进去再调整大小,也可以在push之前就调整好(在我以上的代码中,我人为地将最小堆的size设计成大于等于最大堆的)。
代码里的结构体是自己写的,用了模板元编程,其实写死成整型的也完全可以的,只不过想做成模板,下次直接用了。