堆解决项目收益问题python

本文介绍如何使用Python自定义比较器实现最小成本和最大收益的项目选择策略,通过创建自定义类并重载比较运算符,实现对项目成本和收益的优先级排序,从而优化项目组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义比较器的另一种方法


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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值