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設計成大於等於最大堆的)。
代碼裏的結構體是自己寫的,用了模板元編程,其實寫死成整型的也完全可以的,只不過想做成模板,下次直接用了。