百练+priority_queue应用+最大堆最小堆找出中位数

点击打开链接
//
//  main.cpp
//  test
//
//  Created by 吴有堃 on 2017/9/11.
//  Copyright © 2017年 吴有堃. All rights reserved.
//

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
#define LL long long
using namespace std;
priority_queue<int>lq;
/*struct cmp{
    bool operator()(int a,int b){
        return a>b;
    }
};
 */
priority_queue<int,vector<int>, greater<int> >rq;//自定义优先级
int T=0,N=0;
void push_num(int num)
{
    if(lq.empty())lq.push(num);
    else {
        if(num>=lq.top()){
            rq.push(num);
        }
        else{
            lq.push(num);
        }
    }
    //调整平衡两堆
    int temp=0;
    while (lq.size()>rq.size()+1) {//奇偶判断,减号改成加号,时间3s到1.5s
        temp=lq.top();lq.pop();
        rq.push(temp);
    }
    while(lq.size()<rq.size()){ //奇偶判断
        temp=rq.top();rq.pop();
        lq.push(temp);
    }
}
void pop_num(){
    lq.pop();
    //调整平衡两堆
    int temp=0;
    while (lq.size()>rq.size()+1) {//奇偶判断,减号改成加号,就不超时间了。
        temp=lq.top();lq.pop();
        rq.push(temp);
    }
    while(lq.size()<rq.size()){ //奇偶判断
        temp=rq.top();rq.pop();
        lq.push(temp);
    }
}
int main()
{
    int i=0,num=0;
    char c;
    scanf("%d",&T);
    while (T--) {
        //每次清空堆
        while(!lq.empty()) lq.pop();
        while(!rq.empty()) rq.pop();
        scanf("%d",&N);
        for(i=0;i<N;i++){
            scanf(" %c",&c);
           //getchar();
            //printf("%c\n",c);
            if(c=='I'){
                //getchar();
                scanf("%d",&num);
                push_num(num);
            }
            else if(c=='D'){
                pop_num();
            }
            else if(c=='Q'){
                printf("%d\n",lq.top());///显现队列返回堆顶是用top()
            }
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值