Advertisement
ilnazEPTA

Untitled

May 25th, 2020
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. class PriorityQueue
  4. {
  5. private:
  6. int* arr;
  7. int sz;
  8.  
  9. void up(int i)
  10. {
  11. while (i != 0 && arr[i] > arr[(i - 1) / 2])
  12. {
  13. swap(arr[i], arr[(i - 1) / 2]);
  14. i = (i - 1) / 2;
  15. }
  16. }
  17.  
  18. void down(int i)
  19. {
  20. while (i < sz / 2)
  21. {
  22. int maxI = 2 * i + 1;
  23. if (2 * i + 2 < sz && arr[2 * i + 2] > arr[2 * i + 1])
  24. maxI = 2 * i + 2;
  25. if (arr[i] >= arr[maxI])
  26. return;
  27. swap(arr[i], arr[maxI]);
  28. i = maxI;
  29. }
  30. }
  31.  
  32. public:
  33.  
  34. PriorityQueue(int k)
  35. {
  36. sz = 0;
  37. arr = new int[k];
  38. }
  39.  
  40. ~PriorityQueue()
  41. {
  42. delete arr;
  43. }
  44. void push(int value)
  45. {
  46. arr[sz++] = value;
  47. up(sz - 1);
  48.  
  49. }
  50.  
  51. void pop()
  52. {
  53. if (sz > 0)
  54. {
  55. swap(arr[0], arr[--sz]);
  56. down(0);
  57.  
  58. }
  59. else
  60. return;
  61. }
  62.  
  63. bool empty()
  64. {
  65. return sz == 0;
  66. }
  67.  
  68. const int& top()
  69. {
  70. return arr[0];
  71. }
  72.  
  73. int size()
  74. {
  75. return sz;
  76. }
  77.  
  78. };
  79.  
  80. void error_msg(bool check)
  81. {
  82. if (!check)
  83. cout << "Error occured\n";
  84. }
  85.  
  86. int main()
  87. {
  88. PriorityQueue Q(10);
  89. Q.push(1); Q.push(4);
  90. Q.push(2); Q.push(8);
  91. cout << Q.size();
  92. error_msg(Q.size() == 4);
  93. error_msg(Q.top() == 8);
  94. Q.pop();
  95. cout << Q.size();
  96. error_msg(Q.top() == 4);
  97. Q.pop();
  98. cout << Q.size();
  99. error_msg(Q.top() == 2);
  100. Q.pop();
  101. cout << Q.size();
  102. error_msg(Q.top() == 1);
  103. Q.pop();
  104. cout << Q.size();
  105. error_msg(Q.empty());
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement