python 实现贪心歌手

"贪心歌手"问题是一个经典的贪心算法问题,通常描述为:给定一个歌手列表,每个歌手有一个开始时间和结束时间,以及一个表演费用。目标是在一个特定的时间段内,选择尽可能少的歌手,使得总费用最小,同时确保没有任何时间上的冲突。

以下是一个Python实现的例子:


python复制代码

from typing import List, Tuple
class Singer:
def __init__(self, name: str, start_time: int, end_time: int, cost: int):
self.name = name
self.start_time = start_time
self.end_time = end_time
self.cost = cost
def __lt__(self, other):
# 根据结束时间进行排序
return self.end_time < other.end_time
def greedy_singer(singers: List[Singer], total_time: int) -> Tuple[List[Singer], int]:
# 根据结束时间对歌手进行排序
singers.sort()
selected_singers = []
current_time = 0
total_cost = 0
while current_time < total_time and singers:
# 选择当前结束时间最早的歌手
current_singer = singers[0]
# 如果该歌手的开始时间晚于当前时间,则选择该歌手
if current_singer.start_time >= current_time:
selected_singers.append(current_singer)
current_time = current_singer.end_time
total_cost += current_singer.cost
# 从歌手列表中移除已选择的歌手
singers.pop(0)
else:
# 否则,跳过该歌手,因为它与当前时间冲突
singers.pop(0)
return selected_singers, total_cost
# 示例
singers = [
Singer("Alice", 1, 4, 1000),
Singer("Bob", 2, 5, 2000),
Singer("Charlie", 3, 6, 3000),
Singer("David", 7, 9, 4000),
]
total_time = 10
selected, cost = greedy_singer(singers, total_time)
print("Selected singers:", [s.name for s in selected])
print("Total cost:", cost)

这个例子中,我们首先定义了一个Singer类来表示歌手,然后实现了greedy_singer函数来执行贪心算法。该函数首先对歌手列表进行排序,然后依次选择结束时间最早的歌手,只要它与当前时间没有冲突。最后,它返回被选择的歌手列表以及总费用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数字化信息化智能化解决方案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值