C++ priority_queue 最大堆、最小堆

來源:互聯網
上載者:User

標籤:priority   queue   struct   演算法   

問題描述

通常在刷題的時候,會遇到最大堆、最小堆的問題,這個時候如果自己去實現一個也是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<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是最小堆
其他解決

當然,還有些比較小的較為hack的手段進行。比如要構造一個int類型的最小堆:

priority_queue<int> pq; // pq.push( -1 * v1) ; //pq.push( -1 * v2) ; //pq.push( -1 * v3) ; // 分別是插入v1, v2, v3變數的相反數,那麼pq其實也就變相成為了最小堆,只是每次從pq取值後,要再次乘以-1即可

此外,再貼一份網上的某答案,來源:http://www.cnblogs.com/nirvana-phoenix/archive/2012/05/29/2524344.html

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<node, vector<node>, cmp> q;

C++ priority_queue 最大堆、最小堆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.