poj3784 Running Median

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.

维护一个大根堆和一个小根堆,且保证大根堆里的所有数都比小根堆里的所有数小,而且大根堆的大小等于小根堆或者大1,则大根堆堆顶就是中位数。对于新插入的数,与中位数比较决定插入哪个堆中,插入之后维护一下两个堆的大小。每次维护需要进行常数个堆上的操作,所以复杂度O(nlogn)。

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> > bh;
priority_queue<int,vector<int>,less<int> > sh;
int main()
{
    int i,j,k,m,n,p,q,x,y,z,T,K;
    scanf("%d",&T);
    while (T--)
    {
        scanf("%d%d",&K,&n);
        printf("%d %d\n",K,n/2+1);
        while (!bh.empty()) bh.pop();
        while (!sh.empty()) sh.pop();
        for (i=1;i<=n;i++)
        {
            scanf("%d",&x);
            if (sh.empty()||sh.top()>x) sh.push(x);
            else bh.push(x);
            if (sh.size()>(i+1)/2)
            {
                x=sh.top();
                sh.pop();
                bh.push(x);
            }
            if (sh.size()<(i+1)/2)
            {
                x=bh.top();
                bh.pop();
                sh.push(x);
            }
            if (i&1)
            {
                printf("%d",sh.top());
                if (i==n||(i+1)%20==0)
                  printf("\n");
                else printf(" ");
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值