標籤: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 最大堆、最小堆