STL 最大堆、最小堆的應用

1.priority_queue

priority_queue默認是最大堆,要用最小堆需要比較函數greater<int>

priority_queue<int, vector<int>, less<int>> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;

也可以自定義比較函數

struct cmp
{
     bool operator()(const int &a, const int &b)
    {
         return a > b;
    }
};
priority_queue<int, vector<int>, cmp> minHeap;

如果不是內置類型,也可以

struct cmp
{
     bool operator()(const Node&a, const Node&b)
    {
         return a.val > b.val;
    }
};

2. STL 堆操作

頭文件是#include <algorithm>
一般用到這四個:make_heap()、pop_heap()、push_heap()、sort_heap();
(1)make_heap()構造堆
void make_heap(first_pointer,end_pointer,compare_function);
默認比較函數是(<),即最大堆。
函數的作用是將[begin,end)內的元素處理成堆的結構

(2)push_heap()添加元素到堆
void push_heap(first_pointer,end_pointer,compare_function);
新添加一個元素在末尾,然後重新調整堆序。該算法必須是在一個已經滿足堆序的條件下。
先在vector的末尾添加元素,再調用push_heap

(3)pop_heap()從堆中移出元素
void pop_heap(first_pointer,end_pointer,compare_function);
把堆頂元素取出來,放到了數組或者是vector的末尾。
要取走,則可以使用底部容器(vector)提供的pop_back()函數。
先調用pop_heap再從vector中pop_back元素

(4)sort_heap()對整個堆排序
排序之後的元素就不再是一個合法的堆了。

用法:

void testHeap() {
    vector<int> data{ 3,1,2,7,5 };
    //構造堆,最大堆
    make_heap(data.begin(), data.end(), less<int>());
    //pop堆頂元素,最大的元素
    pop_heap(data.begin(), data.end(), less<int>());
    cout << data.back() << endl;//輸出7
    data.pop_back();
    //往堆中添加元素
    data.push_back(4);
    push_heap(data.begin(), data.end(), less<int>());//調整堆
    //排序
    sort_heap(data.begin(), data.end(), less<int>());
    for (int x : data)
        cout << x << " ";
    cout << endl;//輸出 12345
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章