AcWing 106. 动态中位数

106. 动态中位数 - AcWing题库

坑点:关IO同步时不要使用puts()和printf()
考察:对顶堆,面试必会题

图片来自:AcWing 106. 动态中位数 - AcWing


思路:动态维护对顶堆(使得大顶堆的数始终小于等于小顶堆,并且大顶堆中的数量相对于小顶堆多1或者相等),先插入大顶堆,若大顶堆顶点 大于 小顶堆顶点就 交换 堆顶,若大顶堆数大于 小顶堆数+1,就将大顶堆堆顶弹出并插入小顶堆,那么两个堆之间的数就是中位数了

#include<iostream>
#include<queue>
using namespace std;

int main(){
    cin.tie(0)->sync_with_stdio(false);
    cout.tie(0);
    int T; cin>>T;
    while(T--){
        int id, n; cin>>id>>n;
        cout<<id<<' '<<(n+1)/2<<'\n';
        priority_queue<int> max_heap;
        priority_queue<int,vector<int>,greater<int>> min_heap;
        int cnt = 0;
        for(int i = 1; i <= n; i++){
            int x; cin>>x;
            max_heap.push(x);
            if(min_heap.size() && max_heap.top() > min_heap.top()){
                int t1 = max_heap.top(); max_heap.pop();
                int t2 = min_heap.top(); min_heap.pop();
                max_heap.push(t2); min_heap.push(t1);
            }
            if(max_heap.size() > min_heap.size() + 1){
                min_heap.push(max_heap.top());
                max_heap.pop();
            }
            if(i&1){
                cout<<max_heap.top()<<' ';
                if(++cnt % 10 == 0) cout<<'\n';
            }
        }
        if(cnt%10) cout<<'\n';
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值