"贪心歌手"问题是一个经典的贪心算法问题,通常描述为:给定一个歌手列表,每个歌手有一个开始时间和结束时间,以及一个表演费用。目标是在一个特定的时间段内,选择尽可能少的歌手,使得总费用最小,同时确保没有任何时间上的冲突。
以下是一个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函数来执行贪心算法。该函数首先对歌手列表进行排序,然后依次选择结束时间最早的歌手,只要它与当前时间没有冲突。最后,它返回被选择的歌手列表以及总费用。
2153

被折叠的 条评论
为什么被折叠?



