洛谷P3378 【模板】堆

题目描述

如题,初始小根堆为空,我们需要支持以下3种操作:

操作1: 1 x 表示将x插入到堆中

操作2: 2 输出该小根堆内的最小数

操作3: 3 删除该小根堆内的最小数

输入输出格式

输入格式:

第一行包含一个整数N,表示操作的个数

接下来N行,每行包含1个或2个正整数,表示三种操作,格式如下:

操作1: 1 x

操作2: 2

操作3: 3

输出格式:

包含若干行正整数,每行依次对应一个操作2的结果。

输入输出样例

输入样例#1:
5
1 2
1 5
2
3
2
输出样例#1:
2
5

说明

时空限制:1000ms,128M

数据规模:

对于30%的数据:N<=15

对于70%的数据:N<=10000

对于100%的数据:N<=1000000(注意是6个0。。。不过不要害怕,经过编者实测,堆是可以AC的)

样例说明:

故输出为2、5

此题卡Cin 

#include <algorithm>
#include <cstdio>
using namespace std;
int N,i,j,a,head,heap[1000000*4];
void heap_push(int n)
{
    
    heap[++head]=n;
    int pos=head;
    while(pos>1)
    {
        int next=pos/2;
        if(heap[next]<heap[pos]) break;
        swap(heap[pos],heap[pos/2]);
        pos=next;
    }
}
void heap_pop()
{
    heap[1]=heap[head--];
    int pos=1;
    while(pos*2<=head)
    {
        int next=pos*2;
        if(heap[next]>heap[next+1])
        next++;
        if(heap[next]>=heap[pos]) break;
        swap(heap[next],heap[pos]);
        pos=next;
    }
}
int main()
{
    scanf("%d",&N);
    int type;
    while(N--)
    {
        scanf("%d",&type);
        if(type==1)
        {
            scanf("%d",&a);
            heap_push(a);
        }
        else if(type==2)
        printf("%d
",heap[1]);
        else 
        heap_pop();
    }
    return 0;
}
我们都在命运之湖上荡舟划桨,波浪起伏着而我们无法逃脱孤航。但是假使我们迷失了方向,波浪将指引我们穿越另一天的曙光。
原文地址:https://www.cnblogs.com/ruojisun/p/6486363.html