优先级队列-堆-STL实现

电玩女神 2023-07-12 05:05 149阅读 0赞
  1. 1 #include <cstdio>
  2. 2 #include <iostream>
  3. 3 #include <queue>
  4. 4
  5. 5 using namespace std;
  6. 6
  7. 7 // 默认是最大堆
  8. 8 //
  9. 9
  10. 10 int main()
  11. 11 {
  12. 12 priority_queue<int> heap;
  13. 13 heap.push(3);
  14. 14 heap.push(1);
  15. 15 heap.push(5);
  16. 16 heap.push(4);
  17. 17
  18. 18 while(!heap.empty())
  19. 19 {
  20. 20 cout<<heap.top()<<endl;
  21. 21 heap.pop();
  22. 22 }
  23. 23
  24. 24
  25. 25 // 如何实现最小堆?
  26. 26 priority_queue<int,vector<int>,greater<int>> heap2;
  27. 27 heap2.push(2);
  28. 28 heap2.push(4);
  29. 29 heap2.push(6);
  30. 30 heap2.push(1);
  31. 31 heap2.push(5);
  32. 32
  33. 33 while(!heap2.empty())
  34. 34 {
  35. 35 cout<<heap2.top()<<endl;
  36. 36 heap2.pop();
  37. 37 }
  38. 38 return 0;
  39. 39 }

发表评论

表情:
评论列表 (有 0 条评论,149人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java优先级队列-

    本文章主要讲解了基二叉树之后的知识点堆,讲解了什么是堆,以及堆的应用-优先级队列的使用,用堆来解决TopK问题,作者在最后为各位读者准备了习题以及讲解答案,希望对大家有帮...

    相关 优先级队列

    优先级队列 概念 > 我们知道,队列是一种先进先出的数据结构,但有些情况下,操作的数据可能带有优先级,一般出队列时,可能需要优先级高的元素先出队列,该中场景下,使用