fork download
  1. #include<iostream>
  2. using namespace std;
  3. #include<vector>
  4.  
  5. class heap{
  6. vector<int> pq;
  7. public:
  8.  
  9. void push(int val){
  10. // insert the value in the vector
  11. pq.push_back(val); // O(1);
  12. // fix the heap O(log n);
  13.  
  14. int childidx = pq.size()-1;
  15. int parentidx = (childidx-1)/2;
  16.  
  17. while(parentidx>=0 && pq[childidx]>pq[parentidx]){
  18. swap(pq[childidx],pq[parentidx]);
  19. childidx = parentidx;
  20. parentidx = (childidx-1)/2;
  21. }
  22. }
  23.  
  24. int top(){
  25. return pq[0];
  26. }
  27.  
  28. bool empty(){
  29. return pq.size()==0;
  30. }
  31. };
  32.  
  33. int main(){
  34. heap pq;
  35. pq.push(10);
  36. pq.push(100);
  37. pq.push(50);
  38.  
  39. cout<<"top: "<<pq.top()<<endl;
  40. cout<<pq.empty();
  41. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
top: 100
0