排序——动态中位数(对顶堆)

该博客介绍了如何利用大根堆和小根堆动态维护序列中位数的方法。通过建立两个堆,一个存放较小的一半元素,另一个存放较大的一半元素,确保堆顶元素即为中位数。当新元素到来时,根据其大小决定放入哪个堆,并调整堆以保持堆的性质。最终输出序列的中位数。
摘要由CSDN通过智能技术生成

传送门:106. 动态中位数 - AcWing题库

思路:用一个大根堆和一个小根堆,小根堆存排名m/2+1~m的元素,大根堆存排名1~m/2的元素,

中位数就是大根堆的堆顶元素。

每来一个新的数,如果比中位数小就插入大根堆,不然就插入小根堆。插入完后要保证大根堆的元素个数比小根堆大1。

最后输出中位数。

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n;
priority_queue<int,vector<int>,greater<int>>heap;
priority_queue<int,vector<int>,less<int>>heap1;
const int N=1e5+100;
int a[N];
int main()
{
    int t;
    cin>>t;
    for(int j=1;j<=t;j++)
    {
priority_queue<int,vector<int>,greater<int>>heap;//右半边
priority_queue<int,vector<int>,less<int>>heap1;//左半边
    int p,n;
    cin>>p>>n;
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);

     cout<<p<<' '<<n/2+1<<endl;
     int cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(heap1.size()&&a[i]<=heap1.top())
            heap1.push(a[i]);
        else if(heap1.size()==0)
            heap1.push(a[i]);
        else if(heap1.size()&&a[i]>heap1.top())
        heap.push(a[i]);

        while(heap1.size()<=heap.size())
        {
            heap1.push(heap.top());
            heap.pop();
        }
        while(heap1.size()>=heap.size()+2)
        {
            heap.push(heap1.top());
            heap1.pop();
        }
            if(i%2)
            {
                cnt++;
                
                cout<<heap1.top()<<' ';
                  if(cnt%10==0&&i!=n) 
                    cout<<endl;
            }
    }
    if(j!=t)
    cout<<endl;
    }
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值