C++優先隊列的重載(最小堆、最大堆)


C++優先隊列默認是最大堆,所以如果我們要用到最小堆,就需要進行重載來使用。

priority_queue的頭文件是<queue>.

1.less和greater,不利用struct進行重載。

priority_queue<int, vector<int>, less<int>>s;//less表示按照遞減(從大到小)的順序插入元素
priority_queue<int, vector<int>, greater<int>>s;//greater表示按照遞增(從小到大)的順序插入元素

less默認最大堆,而greater是最小堆。

2.利用struct進行重載。

struct comp {
		comp() {}
		~comp() {}
		bool operator()(const int a,const int b) {
			return a > b;//最小堆,從小到大排序
		}
};
priority_queue<int,vector<int>,comp> pq;//pq是最小堆。

而如果把<改為>,就變成了最大堆,從大到小排序。

struct comp {
		comp() {}
		~comp() {}
		bool operator()(const int a,const int b) {
			return a < b;//最大堆,從大到小排序。
		}
	};

相關題目:

leetcode 692:https://leetcode.com/problems/top-k-frequent-words/description/      Top K Frequent Words    

leetcode 347 https://leetcode.com/problems/top-k-frequent-elements/description/   Top K Frequent Elements


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM