Advertisement
AquaBlitz11

Binary Heap (Recursive)

Mar 12th, 2019
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 100010;
  5. int A[N<<1], n = 0;
  6.  
  7. void sift_down(int i) {
  8.     if (i > n || (A[i] > A[2*i] && A[i] > A[2*i+1]))
  9.         return;
  10.     int p = (A[2*i] > A[2*i+1]) ? (2*i) : (2*i+1);
  11.     swap(A[i], A[p]);
  12.     sift_down(p);
  13. }
  14.  
  15. void sift_up(int i) {
  16.     if (i > 1 && A[i] > A[i/2]) {
  17.         swap(A[i], A[i/2]);
  18.         sift_up(i/2);
  19.     }
  20. }
  21.  
  22. void heapify() {
  23.     for (int i = n/2; i >= 1; --i)
  24.         sift_down(i);
  25. }
  26.  
  27. void insert(int x) {
  28.     A[++n] = x;
  29.     sift_up(n);
  30. }
  31.  
  32. int get_max() {
  33.     return n == 0 ? -1 : A[1];
  34. }
  35.  
  36. void extract_max() {
  37.     if (n == 0)
  38.         return;
  39.     swap(A[n], A[1]);
  40.     A[n--] = 0;
  41.     sift_down(1);
  42. }
  43.  
  44. int main()
  45. {
  46.     scanf("%d", &n);
  47.     for (int i = 1; i <= n; ++i)
  48.         scanf("%d", &A[i]);
  49.     heapify();
  50.  
  51.     int k;
  52.     scanf("%d", &k);
  53.     while (--k)
  54.         extract_max();
  55.     printf("%d\n", get_max());
  56.    
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement