Tarango

Heap DS

Sep 4th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. //Custom Heam Implementation
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. class Max_Heap_PQ {
  6.     int Size, N, *heap,parent,child,Min,ind,t,i,j,cur;
  7.  
  8.     void swap() {
  9.         t = heap[i];
  10.         heap[i] = heap[j];
  11.         heap[j] = t;
  12.     }
  13.  
  14.     void bubbleUp() {
  15.         while (cur > 1) {
  16.             parent = cur / 2;
  17.             if (heap[parent] > heap[cur]) {
  18.                 break;
  19.             }
  20.             i = cur;j = parent;
  21.             swap();
  22.             cur = parent;
  23.         }
  24.     }
  25.  
  26.     void bubbleDown() {
  27.         while (2 * cur <= N) {
  28.             child = 2 * cur;
  29.             if (child < N && heap[child] < heap[child + 1]) {
  30.                 child++;
  31.             }
  32.             if (heap[cur] > heap[child]) {
  33.                 break;
  34.             }
  35.             i = cur;j = child;
  36.             swap();
  37.             cur = child;
  38.         }
  39.     }
  40.  
  41. public:
  42.     Max_Heap_PQ(int Max) {
  43.         Size = Max;
  44.         N = parent = child = Min = t = ind = 0;
  45.         i = j = cur = 0;
  46.         heap = new int[Size + 1];
  47.     }
  48.  
  49.     void insert(int key) {
  50.         N++;
  51.         heap[N] = key;
  52.         cur = N;
  53.         bubbleUp();
  54.     }
  55.  
  56.     int maxKey() {
  57.         return heap[1];
  58.     }
  59.  
  60.     int getSize(){
  61.         return N;
  62.     }
  63.  
  64.     void extractMax() {
  65.         i = 1;j = N;
  66.         swap();
  67.         N--;
  68.         cur = 1;
  69.         bubbleDown();
  70.         heap[N + 1] = -1;
  71.     }
  72. };
  73.  
  74. int main() {
  75.     int N, num , i;
  76.     scanf("%d", &N);
  77.     Max_Heap_PQ pq(N);
  78.     for (i = 0; i < N; i++) {
  79.         scanf("%d", &num);
  80.         pq.insert(num);
  81.     }
  82.  
  83.     while(pq.getSize() != 0){
  84.         printf("%d\n",pq.maxKey());
  85.         pq.extractMax();
  86.     }
  87.  
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment