栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

AcWing 106. 动态中位数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AcWing 106. 动态中位数

106. 动态中位数 - AcWing题库

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

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


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

#include
#include
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< max_heap;
        priority_queue,greater> 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< 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873310.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号