luogu P3378 【模板】堆

本文介绍了一道利用手写堆解决的问题,并通过对比展示了使用标准库优先队列的简洁实现方式。作者首先手动实现了堆的数据结构来处理一系列数值的插入与删除操作,随后又提供了使用C++标准库中的优先队列简化代码的例子。

二次联通门 : 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\n", Queue.top ()); 
                break;
            }
            default :
            {
                Queue.pop (); 
                break;
            }
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/ZlycerQan/p/6805313.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值