Advertisement
tepyotin2

Heap

May 18th, 2025
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. vector<int> heap;
  5.  
  6. void print_heap(){
  7.     for(auto i: heap){
  8.         cout << i << " ";
  9.     }
  10.     cout << '\n';
  11. }
  12.  
  13. int getParent(int val){
  14.     if(val%2 == 0){
  15.         return (val-2)/2;
  16.     }else{
  17.         return (val-1)/2;
  18.     }
  19. }
  20.  
  21. void up_heap(int idx){
  22.     if(idx == 0) return;
  23.     int parent = getParent(idx);
  24.     if(heap[parent]>heap[idx]){
  25.         swap(heap[parent], heap[idx]);
  26.         //cout << "swap: " << heap[parent] << ", " << heap[idx] << '\n';
  27.         up_heap(parent);
  28.     }
  29.     return;
  30.     //if(idx%2 == 0){
  31.         //int parent = ()
  32.     //}
  33.     // 8, 7 => 3, 3, 4 => 1
  34.     // 16, 15 => 7, 1, 2 => 0
  35. }
  36.  
  37. void down_heap(int idx){
  38.     int l = (idx*2)+1;
  39.     int r = (idx*2)+2;
  40.     int mn_idx = idx;
  41.     int size = heap.size();
  42.     if(l<size && heap[l]<heap[mn_idx]){
  43.         mn_idx = l;
  44.     }
  45.     if(r<size && heap[r]<heap[mn_idx]){
  46.         mn_idx = r;
  47.     }
  48.     if(mn_idx != idx){
  49.         swap(heap[idx], heap[mn_idx]);
  50.         down_heap(mn_idx);
  51.     }
  52. }
  53.  
  54. void del(){
  55.     swap(heap[0], heap[heap.size()-1]);
  56.     heap.pop_back();
  57.     down_heap(0);
  58. }
  59.  
  60. int main(){
  61.     //freopen("heap.in", "r", stdin);
  62.    
  63.     cin >> n;
  64.    
  65.     //cout << getParent(15);
  66.     int a, b;
  67.     for(int i=0; i<n; i++){
  68.         cin >> a;
  69.         if(a==1){
  70.             cin >> b;
  71.             //cout << "b: " << b << '\n';
  72.             heap.push_back(b);
  73.             up_heap(heap.size()-1);
  74.         }else if(a==2){
  75.             cout << heap[0] << '\n';
  76.         }else if(a==3){
  77.             del();
  78.         }
  79.     }
  80.     //cout << heap.size() << '\n';
  81.     //print_heap();
  82.     //del();
  83.     //cout << "========" << '\n';
  84.     //cout << heap.size() << '\n';
  85.     //print_heap();
  86.    
  87.     return 0;
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement