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.
classMinHeap:def__init__(self,arr=[]):self.heap=arr[:]self.convert_to_heap()defheapify_up(self,index):parent=(index-1)// 2whileindex>0andself.heap[index]<self.heap[parent]:self.heap[index],self.heap[parent]=self.heap[parent],self.heap[index]index=parentparent=(index-1)// 2defheapify_down(self,index):l=len(self.heap)whileTrue:current=indexleft=(2*index)+1right=(2*index)+2# Check that left and right indexes are lesser than the heap's size and, therefore, are able to access its elements. Else, an index out of range error will be thrown.ifleft<landself.heap[left]<self.heap[current]:current=leftifright<landself.heap[right]<self.heap[current]:current=right# In case that any value computed for the left or right indexes, which correspond to the indexes of current's children, is greater than the heap's size:# * It means that current's value, which hwas updated in the prior iteration, corresponds to a leaft# * Index's value will not be updated and, therefore, will equal current's value, which was set in the prior iteration.ifcurrent==index:breakself.heap[index],self.heap[current]=self.heap[current],self.heap[index]index=currentdefconvert_to_heap(self):foriinrange((len(self.heap)// 2 ) - 1, -1, -1):self.heapify_down(i)definsert(self,val):self.heap.append(val)self.heapify_up(len(self.heap)-1)defpop_root(self):ifnotself.heap:returnNoneroot=self.heap[0]last=self.heap.pop()ifself.heap:self.heap[0]=lastself.heapify_down(0)returnrootdefdelete_value(self,val):ifvalnotinself.heap:returnindex=self.heap.index(val)last=self.heap.pop()ifindex<len(self.heap):self.heap[index]=lastifindex>0andself.heap[index]<self.heap[(index-1)// 2]:self.heapify_up(index)else:self.heapify_down(index)defget_root(self):returnself.heap[0]defcookies(k,A):heap=MinHeap(A)count=0print(f"h = {heap.heap}")whilelen(heap.heap)>1andheap.get_root()<k:flsc=heap.pop_root()slsc=heap.pop_root()print(f"r1 = {flsc}, r1 = {slsc}")ifslscisNone:#Sinohayunasegundagalleta,nosepuedecontinuarreturn-1new_cookie=flsc+(2*slsc)heap.insert(new_cookie)count+=1print(f"heap = {heap.heap}")returncountifheap.get_root()isnotNoneandheap.get_root()>=kelse-1
However, test case 22 was throwing a TLE, so I cahnged the whole code for this instead:
Jesse and Cookies
You are viewing a single comment's thread. Return to all comments →
Guys, I implemented the whole MinHeap and stuff:
However, test case 22 was throwing a TLE, so I cahnged the whole code for this instead: