gt22

Untitled

Dec 20th, 2019
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. struct Heap
  2. {
  3.     vector<int> v, heap_v, pos;  ///v - значения, heap_v - куча индексов, pos - позиции в куче
  4.     int n = 0;
  5.     bool flag_; ///определитель кучи на максимум или минимум
  6.  
  7.     explicit Heap(bool flag){
  8.         heap_v.resize(1);
  9.         heap_v[0] = -1;
  10.         flag_ = flag;
  11.     }
  12.  
  13.     void heap_swap(int i, int j) {
  14.         swap(pos[heap_v[i]], pos[heap_v[j]]);
  15.         swap(heap_v[i], heap_v[j]);
  16.     }
  17.  
  18.     bool is_valid_node(int i) {
  19.         return i > 0 && i <= n;
  20.     }
  21.  
  22.     bool is_valid_parent(int p, int c) {
  23.         return is_valid_node(p) && is_valid_node(c) && (v[heap_v[p]] < v[heap_v[c]])^flag_;
  24.     }
  25.  
  26.     void siftUp(int i)
  27.     {
  28.         int p = i / 2;
  29.         while (is_valid_node(p) && !is_valid_parent(p, i)) {
  30.             heap_swap(i, p);
  31.             i = p;
  32.             p = i / 2;
  33.         }
  34.     }
  35.  
  36.     void siftDown(int i) {
  37.         int l = 2*i;
  38.         while (l <= n){
  39.             if (is_valid_parent(l+1, l)) l++;
  40.             if (is_valid_parent(i, l)) break;
  41.             else {
  42.                 heap_swap(i, l);
  43.                 i = l;
  44.                 l = 2*i;
  45.             }
  46.         }
  47.     }
  48.  
  49.     void Insert(int new_el) {
  50.         v.push_back(new_el);
  51.         pos.push_back(n+1);
  52.         heap_v.push_back(v.size()-1);
  53.         n++;
  54.         siftUp(n);
  55.     }
  56.  
  57.     void Del(int i) {
  58.         ///i = pos[i];
  59.         swap(heap_v[i], heap_v[n]);
  60.  
  61.         heap_v.pop_back();
  62.         n--;
  63.         if(i <= n) {
  64.             pos[heap_v[i]] = i;
  65.             siftUp(i);
  66.             siftDown(i);
  67.         }
  68.     }
  69.  
  70.     int Get(int i) { return v[heap_v[i]];}
  71. };
Advertisement
Add Comment
Please, Sign In to add comment