Running Median POJ - 3784(动态维护中位数问题:”对顶堆“算法/链表+hash)

题意:传送门
题解:动态维护中位数问题,两种解法,解法一是使用对顶堆,建立两个二叉堆,一个小根堆,一个大根堆,依次读入的过程中,设当前长度为 M M M,始终保持:

  1. 序列中从小到大排名为 1 ∼ M 2 1 \sim \frac{M}{2} 12M的整数存储在大根堆priority_queue<int> max_heap中。
  2. 序列中从小到大排名为 M 2 ∼ M \frac{M}{2}\sim M 2MM的整数存储在小根堆priority_queue<int, vector<int>, greater<int>> min_heap

任何时候,如果某一个堆中的元素过多,打破了这个性质,就取出该堆的堆顶插入到另外一个堆,这样一来,小根堆中的中位数就是序列的中位数。
每次新读入一个数 X X X,若 X X X比中位数小,插入到大根堆中,否则插入到小根堆,在插入后再检查并维护上面的两个性质即可。
附上代码(略丑略复杂):

#include<iostream>
#include<cstdio>
#include<queue>
#define mod 998244353
#define pi acos(-1)
#define inf 0x7fffffff
#define eps 1e-6
#define pa pair<int,int>
#define ll long long
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int T,n,id,a,ans,cnt;
int main()
{
    T=read();
    while(T--){
        priority_queue <int,vector<int>,greater<int> > s;
        priority_queue <int,vector<int>,less<int> > b;
        id=read();n=read();cnt=0;
        printf("%d %d\n",id,(n+1)/2);
        for(int i=1;i<=n;i++){
            a=read();
            if(i==1){
                s.push(a);
                ans=a;
            }else if(i%2){
                if(a>ans){
                    s.push(a);
                }else{
                    b.push(a);
                    int tmp=b.top();
                    b.pop();
                    s.push(tmp);
                    ans=s.top();
                }
            }else{
                if(a>ans){
                    s.push(a);
                    int tmp=s.top();
                    s.pop();
                    b.push(tmp);
                    ans=s.top();
                }else{
                    b.push(a);
                }
            }
            if(i%2){
                cnt++;
                printf("%d ",ans);
                if(cnt==10||i==n){
                    cnt=0;
                    printf("\n");
                }
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值