设为首页 加入收藏

TOP

C++ priority_queue 最大堆、最小堆
2015-11-21 01:02:15 来源: 作者: 【 】 浏览:1
Tags:priority_queue 最大 最小

问题描述

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

具体分析

需要注意的是,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
   
     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
   
    , greater
    
      > pq; // 此时greater会调用 > 方法来确认Node的顺序,此时pq是最小堆
    
   

其他解决

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

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

?

struct node{
  int idx;
  int key;
  node(int a=0, int b=0):idx(a), key(b){}
};

struct cmp{
  bool operator()(node a, node b){
    return a.key > b.key;
  }
}; 
priority_queue
   
    , cmp> q;
   
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU1203 DP-01背包 下一篇BZOJ 3308 九月的咖啡店 费用流

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: