POJ 3784 Running Median 动态求中位数 优先队列 小根堆+大根堆

题意:输入M个数,当已输入的个数为奇数个时输出此时的中位数。

一共有M/2+1个中位数要输出,每一行10个。

思路:当数字是奇数的时候才输出中位数,所以是数组的一半我们可以用小跟堆+大根堆来进行维护,设当前序列长度为M,我们始终保持1--M/2的数字存储在大根堆中(从大到小),M/2+1--M的数字存储在小根堆中,当某一个堆中的元素过多的时候,取出该堆的堆顶入另外一个堆。所以,中位数为小根堆的堆顶。

附:优先队列详解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;
const int MAXN =1e3+5;

priority_queue<int,vector<int>,greater<int> >q1; //小根堆 从小到大
priority_queue<int,vector<int>,less<int> >q2;    //大根堆 从大到小

vector<int> g;
void add(int x)
{
    if(q1.empty()){
        q1.push(x);
        return ;
    }
    if(x>q1.top())       //压入数据
        q1.push(x);
    else
        q2.push(x);
    while(q1.size()<q2.size()){    //小根堆数据到大根堆
        q1.push(q2.top());
        q2.pop();
    }
     while(q1.size()>q2.size()+1){  //大根堆数据到小根堆
        q2.push(q1.top());
        q1.pop();
    }
}
int main()
{
    int t,icase=1,n,x;
    scanf("%d",&t);
    while(t--){
        while(!q1.empty())
            q1.pop();
        while(!q2.empty())
            q2.pop();
        g.clear();
        scanf("%d%d",&icase,&n);
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            add(x);
            if(i%2==0)
                g.push_back(q1.top());
        }
        printf("%d %d\n",icase++,(n+1)/2);
        for(int i=0;i<g.size();i++){      //输出
            if(i>0&&i%10==0)
                printf("\n");
            if(i%10)
                printf(" ");
            printf("%d",g[i]);
        }
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/81189680