106.动态中位数

原题链接:106. 动态中位数


解题思路

对顶堆

这是一个很有用的算法,具体思路大致是,开两个堆,一个是大根堆,一个是小根堆,然后小于中位数的都放在大根堆,大于中位数的都放在小根堆,如果说,一个堆的个数大于了当前序列的 1/2 ,那么就将多余的数移过去,直到两个堆数量相等。

样例代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
struct cmp1
{
    bool operator ()(int &a,int &b)
    {
        return a>b;
    }
};
priority_queue <int,vector<int>, cmp1> q1,kong1;
priority_queue <int> q2,kong2;
void init()
{
    int t,x,n,now;
    cin>>t;
    while(t--)
    {
        cin>>x>>n;
        cout<<x<<" "<<(n+1)/2<<endl;
        q1=kong1;
        q2=kong2;
        int cnt=0;
        for (int i=1;i<=n;i++)
        {
            cin>>now;
            if(q1.empty())
                q1.push(now);
            else
            {
                if(now>q1.top()) 
                    q1.push(now);
                else 
                    q2.push(now);
                while(q1.size()<q2.size())
                {
                    q1.push(q2.top());
                    q2.pop();
                }
                while(q1.size()>q2.size()+1)
                {
                    q2.push(q1.top());
                    q1.pop();
                }
            }
            if (i&1)
            {
                cnt++;
                cout<<q1.top()<<" ";
                if (!(cnt%10))
                    cout<<endl;
            }
        }
        if (cnt%10)
            puts("");
    }
}
int main()
{
    init();
    return 0;
}
posted @ 2021-01-14 18:36  hnkjdx_react  阅读(134)  评论(0编辑  收藏  举报