We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Solution using 2 heapify mehods and maintaining a heap through vector
#include<cmath>#include<cstdio>#include<vector>#include<iostream>#include<algorithm>usingnamespacestd;//used to bubble up the newly added element voidheapifyUp(vector<longlongint>&heap){intindex=heap.size()-1;intparent=(index-1)/2;while(parent>=0){if(heap[parent]>heap[index]){swap(heap[parent],heap[index]);index=parent;parent=(index-1)/2;}elsebreak;}}//used to structure the heap after element deletionvoidheapifyDown(vector<longlongint>&heap,longlongintindex=0){intleft=2*index+1;intright=2*index+2;intparent=index;if(left<heap.size()&&heap[parent]>heap[left])parent=left;if(right<heap.size()&&heap[parent]>heap[right])parent=right;if(parent!=index){swap(heap[index],heap[parent]);heapifyDown(heap,parent);}}voidinsertToHeap(vector<longlongint>&heap,longlongintelement){heap.push_back(element);heapifyUp(heap);}voiddeleteFromHeap(vector<longlongint>&heap,longlongintelement){intelementIndex=-1;for(inti=0;i<heap.size();i++){if(heap[i]==element){elementIndex=i;}}swap(heap[elementIndex],heap[heap.size()-1]);heap.resize(heap.size()-1);//problem we were facing /* Fix Heapification After Deletion: 1. After removing an element by swapping it with the last element, instead of just calling heapifyDown, you should check whether the element needs to be "bubbled up" or "bubbled down." 2. If the element that was swapped into the position is smaller than its parent, you should call heapifyUp. 3. If it's larger than its children, you should call heapifyDown.*/if(elementIndex>0&&heap[elementIndex]<heap[(elementIndex-1)/2]){heapifyUp(heap);}elseheapifyDown(heap,elementIndex);}voidprint(vector<longlongint>heap){for(inti:heap)cout<<i<<' ';cout<<endl;}intmain(){/* Enter your code here. Read input from STDIN. Print output to STDOUT */vector<longlongint>heap;longlongintcases=-1,querry,element=-1;cin>>cases;while(cases--){cin>>querry;switch(querry){case1:cin>>element;insertToHeap(heap,element);break;case2:cin>>element;deleteFromHeap(heap,element);break;case3:if(heap.size()>0)cout<<heap[0]<<endl;break;}}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
QHEAP1
You are viewing a single comment's thread. Return to all comments →
Solution using 2 heapify mehods and maintaining a heap through vector