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] 堆顶的最大元素

//如果希望升序排序,就是"<",降序排列就是">"号 //如果希望用其他的参数作为排序条件,只需要把相应的条件改一下(如果改成name),这样结构体就以name作为排序标准 bool comparison(student a,student b){ return a.achievement<b.achievement; } //用来显示学生信息的函数 void show(student *stu,int n) { for(int i = 0; i < n; i++) { cout<<"姓名:"<<stu[i].name<<'\t'<<"成绩:"<<stu[i].achievement<<endl; } } int main() { student stu[] = { {"张三",99},{"李四",87},{"王二",100} ,{"麻子",60}}; cout<<"排序前:"<<endl; show(stu,4); sort(stu,stu+4,comparison); cout<<"排序后:"<<endl; show(stu,4); return 0;

 

posted @ 2016-11-23 15:46  simple_wxl  阅读(819)  评论(0编辑  收藏  举报