luogu P3378 【模板】堆

二次联通门 : luogu P3378 【模板】堆

/*
    一看题
    Woc 竟然还有我没做过的板子题 
    
    于是刷刷刷打了个手写堆
    
    后顺手写上了优先队列..233333 
    
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <queue>

#define Max 6000000

using namespace std;

void read (int &now)
{
    now = 0;
    char word = getchar ();
    bool flag = false;
    while (word < '0' || word > '9')
    {
        if (word == '-')
            flag = true;
        word = getchar ();
    }
    while (word >= '0' && word <= '9')
    {
        now = now * 10 + word - '0';
        word = getchar ();
    }
    if (flag)
        now = -now;
}

int heap [Max]; 
int Count;

void push (int x)
{
    heap [++Count] = x;
    int now = Count;
    while (now > 1)
    {
        int next = now >> 1; 
        if (heap [now] < heap [next])
            swap (heap [now], heap [next]);
        now = next;        
    }
}

int top ()
{
    return heap [1];
}

void pop ()
{
    int now = 1;
    heap [now] = heap [Count--];
    while ((now << 1) <= Count)
    {
        int next = now << 1;
        if ((next | 1) >= Count && heap [next | 1] < heap [next])
            next++;
        if (heap [now] > heap [next])
            swap (heap [now], heap [next]);
        else 
            break;
        now = next;
    }
}

priority_queue <int, vector <int>, greater <int> > Queue;

int main ()
{
    int N;
    read (N);
    int type, x;
    while (N--)
    {
        read (type);
        switch (type)
        {
            case 1:
            {
                read (x);
                Queue.push (x); 
                break;
            }
            case 2:
            {
                printf ("%d
", Queue.top ()); 
                break;
            }
            default :
            {
                Queue.pop (); 
                break;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/ZlycerQan/p/6805313.html