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

来源:互联网 发布:php 捕获异常 编辑:程序博客网 时间:2024/05/09 17:32
点击打开链接
////  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 longusing 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;}