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.
from heapq import heappush, heappop
h= []
p = set()
data = [input().split(' ') for _ in range(int(input()))]
for idx in range(len(data)):
records = data[idx]
if records[0] == '1':
# p.add(records[1],heappush(h, records[1]))
p.add(int(records[1]))
heappush(h, int(records[1]))
elif records[0] == '2':
p.discard(int(records[1]))
elif records[0] == '3':
while h[0] not in p:
heappop(h)
print(h[0])
classMinHeap:def__init__(self):self.heap=[]defadd(self,v):self.heap.append(v)self.__sift_up__(len(self.heap)-1)defdelete(self,v):h=self.heapifh:try:idx=self.heap.index(v)h[idx],h[-1]=h[-1],h[idx]h.pop()ifidx<len(h):self.__sift_down__(idx)self.__sift_up__(idx)exceptValueError:...defprint_min(self):ifself.heap:print(self.heap[0])def__sift_up__(self,idx):# compare and swap with parent upwards repeatedly: (idx-1)//2h=self.heapitem=h[idx]whileidx>0:parent_idx=(idx-1)//2ifitem<h[parent_idx]:h[idx]=h[parent_idx]idx=parent_idxelse:breakh[idx]=itemdef__sift_down__(self,idx):# compare and swap with children downwards repeatedly:h=self.heapsize=len(h)item=h[idx]whileTrue:l_idx,r_idx,min_idx=2*idx+1,2*idx+2,idxifl_idx<sizeandh[l_idx]<item:min_idx=l_idxifr_idx<sizeandh[r_idx]<h[min_idx]:min_idx=r_idxifmin_idx!=idx:h[idx]=h[min_idx]idx=min_idxelse:breakh[idx]=item# Initialize the min-heapminHeap=MinHeap()# Number of operationsnum_of_queries=int(input())# Execute operationsfor_inrange(num_of_queries):op=input().split()op_code=op[0]ifop_code=='1':minHeap.add(int(op[1]))elifop_code=='2':minHeap.delete(int(op[1]))elifop_code=='3':minHeap.print_min()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
from heapq import heappush, heappop h= [] p = set()
data = [input().split(' ') for _ in range(int(input()))] for idx in range(len(data)): records = data[idx] if records[0] == '1': # p.add(records[1],heappush(h, records[1])) p.add(int(records[1])) heappush(h, int(records[1])) elif records[0] == '2': p.discard(int(records[1])) elif records[0] == '3': while h[0] not in p: heappop(h) print(h[0])
Here is hackerrank QHEAP1 problem solution in Python, Java, C++, C and javascript
In JAVA8 :