P3378 【模板】堆

【模板】堆 - 洛谷

/*
 * @Description: To iterate is human, to recurse divine.
 * @Autor: Recursion
 * @Date: 2022-03-21 15:45:40
 * @LastEditTime: 2022-03-21 16:34:03
 */
#include<bits/stdc++.h>
using namespace std;
int heap[1000005],size;

void push(int x)
{
    heap[++size] = x;
    int now = size;
    while(now > 1){
        if(heap[now/2] <= heap[now]) return;
        swap(heap[now],heap[now/2]);
        now = now/2;
    }
}

void pop()
{   
    int now = 1,next;
    heap[1] = heap[size--];
    while(now * 2 <=size){
        next = now * 2;
        if(next + 1 <= size&&heap[next + 1] < heap[next]) next++;//和比较小的儿子交换
        if(heap[next] < heap[now]) swap(heap[next],heap[now]);
        else break;//交换完成
        now = next;
    }
}

int main()
{
    int n,op;
    cin >> n;
    while(n--){
        cin >> op;
        if(op == 1){
            int x;
            cin >> x;
            push(x);
        }
        if(op == 2){
            cout << heap[1] << endl;
        }
        if(op == 3){
            // cout << heap[1] << endl;
            pop();
        }
    }
    // for(int i = 1;i <= size;i ++)
    //     cout << heap[i] << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值