回朔法求活动安排问题python代码
时间: 2023-09-24 14:05:45 浏览: 106
好的,以下是回溯法求解活动安排问题的Python代码:
```
# 定义活动类
class Activity:
def __init__(self, start, end):
self.start = start
self.end = end
# 定义活动选择函数
def activity_selection(activities):
# 按照结束时间排序
activities.sort(key=lambda x: x.end)
# 最初选择第一个活动
selected = [activities[0]]
last_end_time = activities[0].end
# 遍历每个活动
for activity in activities[1:]:
# 如果这个活动的开始时间在上一个活动结束时间之后,就选择它
if activity.start >= last_end_time:
selected.append(activity)
last_end_time = activity.end
# 返回选择的活动列表
return selected
# 测试
activities = [Activity(1, 4), Activity(3, 5), Activity(0, 6), Activity(5, 7), Activity(3, 8), Activity(5, 9), Activity(6, 10), Activity(8, 11), Activity(8, 12), Activity(12, 14)]
selected_activities = activity_selection(activities)
for activity in selected_activities:
print('选择活动:({},{})'.format(activity.start, activity.end))
```
希望这段代码能帮到你,如果还有问题请随时提出。
阅读全文