用二叉堆实现优先队列

#include <cstdio>
#include <iostream>
#define MAXN 100010
using namespace std;
class priority_queue{
    int sizet,heap[MAXN];
public:
    void clear(){
        sizet=0;
    }
    void push(int x){
        int i=sizet++;
        while(i>0){
            int p=(i-1)/2;
            if(heap[p]<x)
            {
                heap[i]=heap[p];
                i=p;
            }
            else break;
        }
        heap[i]=x;
    }
    int top(){
        return heap[0];
    }
    void pop(){
        int i=0;
        heap[i]=heap[--sizet];
        int child=i*2+1;
        while(child<sizet){
            if(child+1<sizet){
                if(heap[child]>heap[child+1]&&heap[child]>heap[i])
                {
                    swap(heap[child],heap[i]);
                    i=child;
                }
                else if(heap[child+1]>heap[child]&&heap[child+1]>heap[i]){
                    swap(heap[child+1],heap[i]);
                    i=child+1;
                }
                else break;
            }
            else{
                if(heap[child]>heap[i]){
                    swap(heap[child],heap[i]);
                    i=child;
                }
                else break;
            }
            child=i*2+1;
        }
    }
    bool empty(){
        if(sizet==0) return true;
        else return false;
    }
};
int n,v;
char op[3];
priority_queue pq;
int main(){
    while(scanf("%d",&n)!=EOF){
        pq.clear();
        for(int i=1;i<=n;i++){
            scanf("%s",op);
            if(op[0]=='A'){
                scanf("%d",&v);
                pq.push(v);
            }
            else {
                printf("%d\n",pq.top());
                pq.pop();
            }
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值