自定义比较器的另一种方法
from heapq import * #默认小根堆
heap=[]
class minCostNode(object):
def __init__(self,c,p):
self.c = c
self.p = p
def __lt__(self, other):
# 运算符重载 好让自己定义的类可以进行比较,相当于比较器
return self.c<other.c
class maxprofileNode(object):
def __init__(self,c,p):
self.c = c
self.p = p
def __lt__(self, other):
return self.p>other.p
# a1 = minCostNode(10,20)
# a2 = minCostNode(15,25)
# a3 = minCostNode(8,30)
# a4 = minCostNode(5,80)
#
#
# heappush(heap,a1)
# heappush(heap,a2)
# heappush(heap,a3)
# heappush(heap,a4)
# a = heappop(heap)
# print(a.c)
# b = heappop(heap)
# print(b.c)
#5,8
e1 = maxprofileNode(10,20)
e2 = maxprofileNode(15,80)
e3 = maxprofileNode(8,50)
e4 = maxprofileNode(5,30)
heappush(heap,e1)
heappush(heap,e2)
heappush(heap,e3)
heappush(heap,e4)
f = heappop(heap)
print(f.c)
#15
#File Name : 项目收益问题(IPO).py
import heapq
# 建立项目节点,包括项目花费与收益
class minCostNode(object):
def __init__(self,c,p):
self.c = c
self.p = p
def __lt__(self, other):
return self.c<other.c
class maxprofileNode(object):
def __init__(self,c,p):
self.c = c
self.p = p
def __lt__(self, other):
return self.p>other.p
def get_max_profits(k,w,c,p):
# k 最多做的项目数
# w 启动资金
# c 花费的数组
# p 利润的数组
#min_cost_heap = []
all_node = []
# 按花费的小根堆
#max_profits_heap = []
#node_lis
for i in range(len(c)):
node = minCostNode(c[i],p[i])
all_node.append(node)
print(all_node)
min_cost_heap = []
max_profits_heap = []
for i in range(len(all_node)):
heapq.heappush(min_cost_heap,all_node[i])
for i in range(k):
while min_cost_heap and min_cost_heap[0].c<=w:
p1 = heapq.heappop(min_cost_heap)
node = maxprofileNode(p1.c,p1.p)
heapq.heappush(max_profits_heap,node)
if not max_profits_heap:
return w
w = w+heapq.heappop(max_profits_heap).p
return w
k = 5
w = 100
c = [10,20,50,80,200]
p = [5,10,15,20,25]
a1 = get_max_profits(k,w,c,p)
print(a1)