洛谷P1168中位数

如果用循环+sort的话肯定会爆,所以这里介绍一种简单的方法:

用两个堆,一个大根堆,一个小根堆。

-------------------------------                ------------------------------------

1      3        5      7    8  |                |     13   16     17    18

-------------------------------                ------------------------------------

 大根堆                                                            小根堆

这样大根堆堆顶就是答案了。

中位数 传送门

代码如下:

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=100005;
int n;
priority_queue<int> q1;
priority_queue<int,vector<int>,greater<int> > q2;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        int a;
        scanf("%d",&a);
        int s1=q1.size();
        int s2=q2.size();
        if(s1==0) q1.push(a);
        else{
            int a1=q1.top();
            if(a<=a1){
                q1.push(a);
                s1++;
            }
            else{
                q2.push(a);
                s2++;
            }
        }
        while(s1-s2>1){
            q2.push(q1.top());
            q1.pop();
            s1--;
            s2++;
        }
        while(s2-s1>=1){
            s2--;
            s1++;
            q1.push(q2.top());
            q2.pop();
        }
        if(i%2==1) printf("%d\n",q1.top());
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值