templates/heap.cpp
compilable
$cat templates/heap
Binary Heap
Min/max binary heap with push, pop, and top in O(log n).
#heap#priority-queue#binary-heap
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
struct Heap {
vector<int> a;
int sz = 0;
Heap() { a.push_back(0); }
bool cmp(int i, int j) { return a[i] < a[j]; }
void up(int i) {
while (i > 1 && cmp(i, i / 2)) {
swap(a[i], a[i / 2]);
i /= 2;
}
}
void down(int i) {
while (2 * i <= sz) {
int j = 2 * i;
if (j + 1 <= sz && cmp(j + 1, j)) j++;
if (cmp(i, j)) break;
swap(a[i], a[j]);
i = j;
}
}
void push(int x) { a.push_back(x); sz++; up(sz); }
void pop() { swap(a[1], a[sz]); a.pop_back(); sz--; down(1); }
int top() { return a[1]; }
bool empty() { return sz == 0; }
int size() { return sz; }
};38 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Binary Heap
Complete binary tree stored in a 1-indexed array. Parent of node is , children are and .
Operations
push(x) — insert element, bubble up to restore heap propertypop() — remove top, swap with last, bubble downtop() — peek at min/max elementHeap Property
When to Use
priority_queue works internallystd::priority_queueNotes
priority_queue, greater> is usually sufficient for min-heap