参考:
https://blog.csdn.net/minxihou/article/details/51857518
from heapq import * #默认小根堆
heap=[]
heappush(heap,4)
heappush(heap,3)
heappush(heap,5)
heappush(heap,9)
heappush(heap,0)
print(heappop(heap))
print(heappop(heap))
print(heappop(heap))
print(heappop(heap))
print(heappop(heap))
from heapq import * #默认小根堆
heap=[]
heappush(heap,[1,17])
heappush(heap,[4,3])
heappush(heap,[5,19])
heappush(heap,[2,73])
heappush(heap,[3,84])
print(nsmallest(len(heap),heap,key=lambda x:x[0]))
print(nlargest(len(heap),heap,key=lambda x:x[0]))
题目:
一块金条切成两半,是需要花费和长度数值一样的铜板的。比如长度为20的 金条,不管切成长度多大的两半,都要花费20个铜板。一群人想整分整块金 条,怎么分最省铜板?
例如,给定数组{10,20,30},代表一共三个人,整块金条长度为10+20+30=60. 金条要分成10,20,30三个部分。 如果, 先把长度60的金条分成10和50,花费60 再把长度50的金条分成20和30,花费50 一共花费110铜板。但是如果, 先把长度60的金条分成30和30,花费60 再把长度30金条分成10和20,花费30 一共花费90铜板。输入一个数组,返回分割的最小代价。
#贪心,切金条,利用堆结构,知道叶节点值,求非叶节点和最小,每次弹出最小的两个,组合再扔回堆,再弹出,直到全都加完
from heapq import *
arr=[10,20,30]
heap=[]
for i in range(len(arr)):
heappush(heap,arr[i])
while len(heap)>1:
item1= heappop(heap)
item2 = heappop(heap)
c=item1+item2
heappush(heap,c)
print(c)
题目:
输入: 参数1,正数数组costs 参数2,正数数组profits 参数3,正数k 参数4,正数m costs[i]表示i号项目的花费 profits[i]表示i号项目在扣除花费之后还能挣到的钱(利润) k表示你不能并行、只能串行的最多做k个项目 m表示你初始的资金
**说明:**你每做完一个项目,马上获得的收益,可以支持你去做下一个 项目。
输出: 你最后获得的最大钱数。
from heapq import *
class bigHeap(): #大根堆实现
def __init__(self):
self.arr=list()
def heap_insert(self,val):
heappush(self.arr,[x*-1 for x in val]) #列表
def heapify(self):
heapify(self.arr)
def heap_pop(self):
return [x*-1 for x in heappop(self.arr)] #列表
def get_top(self):
if not self.arr:
return
return [x*-1 for x in self.arr[0]] #列表
def cal_return(k,arr,m):
cost_heap=[]
for i in range(len(arr)): #按照花费放进小根堆
heappush(cost_heap,arr[i])
value_heap=bigHeap()
profit=0
while k>0 and m>0:
while cost_heap and m>=cost_heap[0][0] : #将满足投资条件的弹进大根堆
q=heappop(cost_heap)
q[0],q[1]=q[1],q[0] #交换位置,以收益排成大根堆,默认按第一个元素进行排列
value_heap.heap_insert(q)
ll=value_heap.heap_pop()
m=m-ll[1]+ll[0]
profit+=ll[0]
k-=1
return profit
if __name__=="__main__":
arr=[[2,5],[4,6],[3,8],[6,4]]
m=3
k=2
print(cal_return(k,arr,m))