Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to make a min heap in C++?

Tags:

I'm very new to C++, and I was wondering if there was a way to make a min heap in C++ from the standard library.

like image 426
Alex Avatar asked May 07 '10 05:05

Alex


People also ask

How do I create a min-heap?

To build a min heap we:Create a new child node at the end of the heap (last level). Add the new key to that node (append it to the array). Move the child up until you reach the root node and the heap property is satisfied.

How do I add elements to a min-heap?

First, always insert at the bottom of the tree. The initial position of the inserted element is at the last level. We will now need to update the position of this element so that the min-heap property is satisfied. Since the root node of every sub-tree must be the minimum, check the sub-tree of its immediate parent.

How can you implement minimum heap using priority queue?

Another method for making min-heap using default priority_queue: This is frequently used in Competitive Programming. We first multiply all elements with (-1). Then we create a max heap (max heap is the default for priority queue).


1 Answers

Use make_heap() and friends, defined in <algorithm>, or use priority_queue, defined in <queue>. The priority_queue uses make_heap and friends underneath.

#include <queue> // functional,iostream,ctime,cstdlib
using namespace std;

int main(int argc, char* argv[])
{
    srand(time(0));
    priority_queue<int,vector<int>,greater<int> > q;
    for( int i = 0; i != 10; ++i ) q.push(rand()%10);
    cout << "Min-heap, popped one by one: ";
    while( ! q.empty() ) {
        cout << q.top() << ' ';  // 0 3 3 3 4 5 5 6 8 9
        q.pop();
    }
    cout << endl;
    return 0;
}
like image 54
wilhelmtell Avatar answered Oct 15 '22 09:10

wilhelmtell