百练 / 2017计算机学科夏令营上机考试 G:实现堆结构

百练 / 2017计算机学科夏令营上机考试 G:实现堆结构

手搓小顶堆

# 百练 / 2017计算机学科夏令营上机考试 G:实现堆结构
# http://bailian.openjudge.cn/xly2017/g/
# http://bailian.openjudge.cn/practice/4078/
# Author:NitrogenousFish
# github:https://github.com/NITROGENousFish/
def getLeft(pos):
    return 2*pos+1
def getRight(pos):
    return 2*pos+2

class Heap:
    def __init__(self):
        self.storage=[]
    def swap(self,a,b):
        temp = self.storage[a]
        self.storage[a] = self.storage[b]
        self.storage[b] = temp
    def getFather(self,index):
        #返回父节点的下标
        if index == 0 or index > len(self.storage) -1:
            return None
        else:
            return (index -1) >> 1
    def siftup(self,index):
        while self.getFather(index) is not None and self.storage[self.getFather(index)]>self.storage[index]:
            self.swap(self.getFather(index),index)
            index = self.getFather(index)
        
    def insert(self,content):
        self.storage.append(content)
        self.siftup(len(self.storage)-1)
        # print(self.storage)
    
    def siftdown(self,index):
        total_index = len(self.storage) -1
        while True:
            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
    def pop(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 in range(m):
        out = list(map(int,input().split()))
        if len(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 in range(m):
        out = list(map(int,input().split()))
        if len(out) == 2:
            heapq.heappush(num,out[1])
        else:
            print(heapq.heappop(num))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值