luogu P3378 【模板】堆

题目大意

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

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

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

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

输入格式

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

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

操作1: 1 x

操作2: 2

操作3: 3

输出格式:

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

输入样例

5

1 2

1 5

2

3

2
输出样例

2

5


code

#include<bits/stdc++.h>
using namespace std;


const int N = 1e6+5;
int n,i,t,x,tot = 0,now,nxt;
int v[N];


inline int read()
{
    int x = 0;
    char ch =getchar();
    while(ch < '0' || ch > '9') ch = getchar();
    while(ch >='0' && ch <= '9')
    {
        x = x*10 + ch-'0';
        ch = getchar();
    }
    return x;
}

inline void insert()
{
    x = read();
    v[++tot] = x;
    now = tot;
    while(v[now>>1] > v[now]) 
    {
        swap(v[now>>1] , v[now]);
        now = now>>1;
    }
}


inline void del()
{
    v[1] = v[tot--];
    now = 1;
    while((now<<1) <= tot)
    {
        nxt = now<<1;
        if(nxt+1 <= tot && v[nxt+1] < v[nxt]) nxt++;
        if(v[nxt] < v[now]) swap(v[now],v[nxt]);
        else break;
        now = nxt; 
    }
}

int main()
{
    n = read();
    for(i = 1;i <= n;i++)
    {
        t = read();
        if(t == 1) insert();
        if(t == 2) printf("%d\n",v[1]);
        if(t == 3) del();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Mark-X/p/11404640.html