Advertisement
pratiyush7

Min Heap

Nov 20th, 2021
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <map>
  5. #include <iostream>
  6. #include <climits>
  7. #include <algorithm>
  8. using namespace std;
  9.  
  10. // Solves this problem: https://www.hackerrank.com/challenges/qheap1/problem?isFullScreen=true
  11.  
  12. const int M = 4e5  + 50;
  13.  
  14.  
  15. int heap[M];
  16. int len;
  17.  
  18. int parent(int i)
  19. {
  20.     return (i-1)/2;
  21. }
  22.  
  23. int left(int i)
  24. {
  25.     return (2*i + 1);
  26. }
  27.  
  28. int right(int i)
  29. {
  30.     return (2*i + 2);
  31. }
  32.  
  33. void insert(int x)
  34. {
  35.     int i = len;
  36.     heap[i] = x;
  37.     ++len;
  38.     while(i!=0 && heap[parent(i)] > heap[i])
  39.     {
  40.         swap(heap[i],heap[parent(i)]);
  41.         i = parent(i);
  42.     }
  43. }
  44.  
  45. void minify(int i)
  46. {
  47.     int l = left(i);
  48.     int r = right(i);
  49.     int smallest = i;
  50.     if(l<len && heap[l] < heap[smallest])
  51.         smallest = l;
  52.     if(r < len && heap[r] < heap[smallest])
  53.         smallest = r;
  54.     if(smallest != i)
  55.     {
  56.         swap(heap[i],heap[smallest]);
  57.         minify(smallest);
  58.     }
  59.        
  60. }
  61.  
  62. void del(int x)
  63. {
  64.     int i;
  65.     for(i = 0 ;i< len;i++)
  66.         if(heap[i] == x)
  67.             break;
  68.     heap[i] = INT_MIN;
  69.     while(i != 0 && heap[parent(i)] > heap[i])
  70.     {
  71.         swap(heap[parent(i)],heap[i]);
  72.         i = parent(i);
  73.     }
  74.     heap[0] = heap[len-1];
  75.     --len;
  76.     minify(0);
  77. }
  78.  
  79. int main()
  80. {
  81.     len = 0;
  82.     int q;
  83.     cin>>q;
  84.     while(q--)
  85.     {
  86.         int t;
  87.         cin>>t;
  88.         if(t == 3)
  89.         {
  90.             cout<<heap[0]<<endl;
  91.             continue;
  92.         }
  93.         int v;
  94.         cin>>v;
  95.         if(t == 1)
  96.             insert(v);
  97.         else
  98.             del(v);
  99.     }
  100. }
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement