POJ3784 Running Median

时间:2022-02-23 03:33:27
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 1670   Accepted: 823

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

Source

对于每个奇数次读入,输出当前已有序列的中位数

维护两个堆,一个大根堆,一个小根堆。大根堆里存较小的数,小根堆里存较大的数。维护好以后,小根堆顶就是中位数。

每次新加入一个数,若该数比中位数大,存入小根堆,否则存入大根堆。

限制小根堆里的数最多比大根堆大1,若不满足,就把小根堆的堆顶弹到大根堆。

以下是代码,基本是抄的233。

结构体里写的是小根堆,为了缩减代码长度,把大根堆取负,也按照小根堆的算法算,就能维护出大根堆。

注意输出格式。mod20==19是为了输出10个中位数就换一行。

 /*by SilverN*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int mxn=;
struct pile{
int h[];
int cnt;
void insert(int x){//插入
h[++cnt]=x;
int k=cnt;
while(k> && h[k]<h[k>>]){//维护
swap(h[k],h[k>>]);
k>>=;
}
}
void pop(){
int k=;
h[]=h[cnt];//把末尾元素顶上来
h[cnt--]=;
while(k<=cnt){
if(h[k]>h[k+] && k<cnt)k++;//在两个子节点中找较小的
if(h[k]<h[k>>])swap(h[k],h[k>>]),k<<=;//把较小的顶上去
else break;//满足性质,退出
}
}
}big,small,empty;
void ins(int x){
if(x<=-big.h[])
big.insert(-x);
else small.insert(x);
while(small.cnt>big.cnt) big.insert(-small.h[]),small.pop();
while(big.cnt>small.cnt+) small.insert(-big.h[]),big.pop();
}
int n,m;
int main(){
int T;
scanf("%d",&T);
int i,j;
while(T--){
big=small=empty;//初始化
scanf("%d%d",&n,&m);
int num;
printf("%d %d\n",n,(m+)>>);
for(i=;i<=m;i++){
scanf("%d",&num);
ins(num);
if(i&){//奇数
printf("%d",-big.h[]);
if(i==m)printf("\n");else printf(" ");
if(i%==)printf("\n");
}
}
}
return ;
}