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



模拟小根堆
的插入和查询

#include<bits/stdc++.h>
using namespace std;
//input by bxd
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i>=(b);--i)
#define RI(n) scanf("%d",&(n))
#define RII(n,m) scanf("%d%d",&n,&m)
#define RIII(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define RS(s) scanf("%s",s);
#define ll long long
#define pb push_back
#define REP(i,N)  for(int i=0;i<(N);i++)
#define CLR(A,v)  memset(A,v,sizeof A)
//////////////////////////////////
#define inf 0x3f3f3f3f
const int N=100000000+5;
int heap[N];
int pos=0;

void push(int x)
{
    heap[++pos]=x;
    int now=pos;
    while(now)
    {
        int nex=now>>1;
        if(heap[nex]>heap[now])swap(heap[nex],heap[now]);
        else break;
        now=nex;
    }
}
void pop()
{
    swap(heap[1],heap[pos]);
    pos--;
    int now=1;
    while((now<<1)<=pos)
    {
        int nex=now<<1;
        if(nex+1<=pos&&heap[nex+1]<heap[nex])nex++;
        if(heap[now]>heap[nex])swap(heap[now],heap[nex]);
        else break;
        now=nex;
    }
}
int main()
{
    int n;
    RI(n);
    rep(i,1,n)
    {
        int a;RI(a);
        if(a==1)
        {
            int b;RI(b);
            push(b);
        }
        else if(a==2)
        {
            cout<<heap[1]<<endl;
        }
        else if(a==3)
            pop();
    }
    return 0;
}
View Code





原文地址:https://www.cnblogs.com/bxd123/p/10803534.html