【模板】堆

P3378 【模板】堆

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 1e6;
int h[N], s;

void up(int u)
{
    while(u / 2 && h[u / 2] > h[u])
    {
        swap(h[u / 2], h[u]);
        u /= 2;
    }
}

void down(int u)
{
    int t = u;
    if(u * 2 <= s && h[u * 2] < h[t]) t = u * 2;
    if(u * 2 + 1 <= s && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
    if(u != t)
    {
        swap(h[u], h[t]);
        down(t);
    }
}

int main()
{
    int n; cin >> n;
    while(n --)
    {
        int k;
        cin >> k;
        if(k == 1)
        {
            int x;
            cin >> x;
            s ++;
            h[s] = x;
            up(s);
        }
        else if(k == 2)
        {
            cout << h[1] << endl;
        }
        else if(k == 3)
        {
            swap(h[1], h[s]);
            s--;
            down(1);
        }
    }
}
原文地址:https://www.cnblogs.com/longxue1991/p/13086477.html