Introduction
Min Heap: minimum element will be at the top
Max Heap: maximum element will be at the top
priority_queue<int> // Max heap
priority_queue<int, vector<int>, greater<int>> // Min heap
// Here it will compare only the first parameter in the pair
// Max Heap
priority_queue<pair<int, int>>
// Min Heap
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
struct cmp {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
// For a min-heap (smallest second element pops first):
return a.second > b.second;
// For a max-heap (largest second element pops first),
return a.second < b.second;
}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp>>> // Here it will compare only the second parameter in the pair
// Heap Operations
priority_queue<int> pq;
// Insert an element
pq.push(element); // O(log N)
// Delete the root element
pq.pop(); // O(log N)
// Take the root element but not delete it
pq.top(); // O(1)
// Check if the pq is empty or not
pq.empty(); // return true or false
// Size of pq
pq.size(); // O(1)