在第一場CCCC選拔賽上,有一關於系統調度的水題。利用優先隊列很容易AC。
// 由於比賽時花費了不少時間研究如何定義priority_queue的比較函數,決心把STL熟練掌握...
Queue
首先來看http://www.cplusplus.com/reference/queue/queue/對STL Queue容器的介紹。
在C++中只要#include<queue>可使用隊列類,常用的成員函數有
1. push
2. pop
3. size
4. empty
5. front
6. back // 目前還沒使用過,留意一下
隊列在BFS時經常使用,已經比較熟悉其用法。
Priority_queue
在CPP網站上同樣也有優先隊列的詳細介紹。在《數據結構與算法分析》一書上,堆(heap)等同於優先隊列,或者准確地說,優先隊列是通過堆實現的。
相比隊列,priority_queue的成員函數名基本一致,除了將front改為top,都是獲取隊首元素。
1. push
2. pop
3. size
4. empty
5. top
-
一般情況下使用方式與vector,queue一樣,需要自定義數據類型時稍有點不同了。
priority_queue<int, vector<int>, greater<int> > q; // 小頂堆 priority_queue<int, vector<int>, less<int> > q; // 大頂堆,默認 // 自定義數據結構 // 方式一 struct Node{ int x, y; Node(int a = 0, int b= 0):x(a), y(b) {} }; struct cmp{ bool operator() (const Node& a, const Node& b ){ if (a.x == b.x) return a.y > b.y; return a.x > b.x; } }; priority_queue<Node, vector<Node>, cmp> q; // 方式二 struct Node{ int x, y; Node(int a = 0, int b= 0):x(a), y(b) {} }; bool operator < (const Node& a, const Node& b ){ if (a.x == b.x) return a.y > b.y; return a.x > b.x; }
上次比賽時,我忘了如何加上vector<int>部分,摸索半天通過方式二(編寫的友元函數實現)才成功調試好代碼,浪費了大量的時間。希望以后能記牢,平常多加練習達到熟練運用的水平^_^
STL 堆操作
// 參考COPY自https://blog.csdn.net/my_lovely_lemon_tree/article/details/78007316
頭文件是#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()對整個堆排序
排序之后的元素就不再是一個合法的堆了。