2020 C++ priority_queue 最大堆与最小堆介绍

1、问题描述

通常在刷题的时候,会遇到最大堆、最小堆的问题,这个时候如果自己去实现一个也是OK的,但是通常时间不太够,那么如何处理?这时,就可以借助C++ STL的priority_queue。

2、具体分析
  • 需要注意的是,C++ STL默认的priority_queue是将优先级最大的放在队列最前面,也即是最大堆。那么如何实现最小堆呢?

假设有如下一个struct:

struct Node {
    int value;
    int idx;
    Node (int v, int i): value(v), idx(i) {}
    friend bool operator < (const struct Node &n1, const struct Node &n2) ; 
};

inline bool operator < (const struct Node &n1, const struct Node &n2) {
    return n1.value < n2.value;
}

priority_queue<Node> pq; // 此时pq为最大堆

如果需要最小堆,则需要如下实现:

struct Node {
    int value;
    int idx;
    Node (int v, int i): value(v), idx(i) {}
//  friend bool operator < (const struct Node &n1, const struct Node &n2) ;
    friend bool operator > (const struct Node &n1, const struct Node &n2) ;
}; 

inline bool operator > (const struct Node &n1, const struct Node &n2) {
    return n1.value > n2.value;
}

priority_queue<Node, vector<Node>, greater<Node> > pq; // 此时greater会调用 > 方法来确认Node的顺序,此时pq是最小堆
3、其他方式

当然,还有些比较小的较为hack的手段进行。比如要构造一个int类型的最小堆:

priority_queue<int> pq; // 
pq.push( -1 * v1) ; //
pq.push( -1 * v2) ; //
pq.push( -1 * v3) ; // 分别是插入v1, v2, v3变量的相反数,那么pq其实也就变相成为了最小堆,只是每次从pq取值后,要再次乘以-1即可
4、用最小堆解决问题

Codeforces Round #536 (Div. 2), problem: (D) Lunar New Year and a Wander

推荐阅读这篇博客——Codeforces Round #536 (Div. 2), problem: (D) Lunar New Year and a Wander 【最小堆+bfs】

学如逆水行舟,不进则退
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一百个Chocolate

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值