# 百练 / 2017计算机学科夏令营上机考试 G:实现堆结构# http://bailian.openjudge.cn/xly2017/g/# http://bailian.openjudge.cn/practice/4078/# Author:NitrogenousFish# github:https://github.com/NITROGENousFish/defgetLeft(pos):return2*pos+1defgetRight(pos):return2*pos+2classHeap:def__init__(self):
self.storage=[]defswap(self,a,b):
temp = self.storage[a]
self.storage[a]= self.storage[b]
self.storage[b]= temp
defgetFather(self,index):#返回父节点的下标if index ==0or index >len(self.storage)-1:returnNoneelse:return(index -1)>>1defsiftup(self,index):while self.getFather(index)isnotNoneand self.storage[self.getFather(index)]>self.storage[index]:
self.swap(self.getFather(index),index)
index = self.getFather(index)definsert(self,content):
self.storage.append(content)
self.siftup(len(self.storage)-1)# print(self.storage)defsiftdown(self,index):
total_index =len(self.storage)-1whileTrue:
maxvalue_index = index
if getLeft(index)<= total_index and self.storage[getLeft(index)]< self.storage[maxvalue_index]:
maxvalue_index = getLeft(index)if getRight(index)<= total_index and self.storage[ getRight(index)]< self.storage[maxvalue_index]and self.storage[ getRight(index)]< self.storage[getLeft(index)]:
maxvalue_index = getRight(index)if maxvalue_index == index:break
self.swap(index,maxvalue_index)
index = maxvalue_index
defpop(self):
out = self.storage[0]
self.swap(0,-1)
self.storage.pop(-1)
self.siftdown(0)# print(self.storage) return out
if __name__ =="__main__":
num = Heap()
m =int(input())for i inrange(m):
out =list(map(int,input().split()))iflen(out)==2:
num.insert(out[1])else:print(num.pop())
或者用自带的heapq
# 百练 / 2017计算机学科夏令营上机考试 F:Full Tank?# http://bailian.openjudge.cn/xly2017/F/# http://bailian.openjudge.cn/practice/3761/# Author:NitrogenousFish# github:https://github.com/NITROGENousFish/import heapq
if __name__ =="__main__":
num =[]
heapq.heapify(num)
m =int(input())for i inrange(m):
out =list(map(int,input().split()))iflen(out)==2:
heapq.heappush(num,out[1])else:print(heapq.heappop(num))