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