c++/java/python priority_que实现最大堆和最小堆

#include<iostream>
#include<vector>
#include<math.h>
#include<string>
#include<algorithm>
using namespace std;
#include<map>
#include<stack>
#include<unordered_set>
#include<string.h>
#include<queue>
struct cmp
{
bool operator()(int a, int b)
{
return a > b;
}
};
priority_queue<int> maxHeap;
priority_queue<int,vector<int>,cmp> minHeap;
int main()

{
maxHeap.push(2);
maxHeap.push(3);
maxHeap.push(1);
int len = maxHeap.size();
for (int i = 0; i < len; i++)
{

cout << maxHeap.top() << endl;
maxHeap.pop();
}
minHeap.push(3);
minHeap.push(2);
minHeap.push(101);
int len2 = minHeap.size();
for (int i = 0; i < len2; i++)
{
cout << minHeap.top() << endl;
minHeap.pop();
}
return 0;
}

java中priorityqueue是最小堆,而c++是最大堆

PriorityQueue<Integer> minHeap=new PriorityQueue<>(11);
PriorityQueue<Integer> maxHeap=new PriorityQueue<>(11, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return (o2-o1);
}
});

//python中默认的heapq中是最小堆,和java类似,最大堆的实现trick是入堆时候-num,出堆的时候再加上-num就可以了

具体:import heapq

minHeap=[]

heappush(minHeap,11)

heappush(minHeap,12);

heappop(minHeap)//出堆

minHeap[0] 堆顶的最大元素

上一篇:page_print


下一篇:基于Nginx 和 uwsgi 搭建 django.