Tossaporn Saengja

Heap

คำอธิบาย

https://www.geeksforgeeks.org/wp-content/uploads/MinHeapAndMaxHeap.png

https://www.geeksforgeeks.org/wp-content/uploads/MinHeapAndMaxHeap.png

คุณสมบัติ

Binary Heap เป็น Binary Tree ที่มีคุณสมบัติเพิ่มเติมดังนี้

Operations (Min Heap)

ตัวอย่างการ implement

#include <bits/stdc++.h>
int d[100010] = {};
int cnt = 0, heap[100010] = {};

using namespace std;

void jom(int i) {
  while (i <= cnt / 2) {
    int j = i;
    if (i * 2 < cnt)
      if (d[heap[i * 2]] < d[heap[j]])
        j = i * 2;
    if (i * 2 + 1 < cnt)
      if (d[heap[i * 2 + 1]] < d[heap[j]])
        j = i * 2 + 1;
    if (j == i)
      break;
    swap(heap[i], heap[j]);
    i = j;
  }
}

void loy(int i) {
  while (i > 1) {
    if (d[heap[i / 2]] > d[heap[i]]) {
      swap(heap[i / 2], heap[i]);
      i /= 2;
    } else
      break;
  }
}

void insertKey(int k) {
  // First insert the new key at the end
  d[++cnt] = k;
  heap[cnt] = cnt;

  // Fix the min heap property if it is violated
  loy(cnt);
}

void decreaseKey(int i, int new_val) {
  d[heap[i]] = new_val;
  loy(i);
}

// Method to remove minimum element (or root) from min heap
int extractMin() {
  // Store the minimum value, and remove it from heap
  int root = heap[1];
  heap[1] = heap[cnt];
  cnt--;
  jom(1);
  return d[root];
}

// This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin()
void deleteKey(int i) {
  decreaseKey(i, INT_MIN);
  extractMin();
}

int getMin() { return d[heap[1]]; }

void printHeap() {
  for (int i = 1; i <= cnt; i++) {
    printf("%d ", d[heap[i]]);
  }
  printf("\n");
}

int main() {
  insertKey(3);
  insertKey(2);
  printHeap();
  deleteKey(1);
  printHeap();
  insertKey(15);
  insertKey(5);
  insertKey(4);
  insertKey(45);
  printHeap();
  printf("extractMin %d\n", extractMin());
  printHeap();
  printf("getMin %d\n", getMin());
  decreaseKey(2, 1);
  printHeap();
  printf("getMin %d\n", getMin());
  return 0;
}