编辑代码

def optimize_tour(total_days, duration, scores):
    # 创建一个二维数组dp,其中dp[i][j]表示在前i个景点中,使用j天能够获得的最大评分
    dp = [[0 for _ in range(total_days + 1)] for _ in range(len(duration) + 1)]

    # 填充dp数组
    for i in range(1, len(duration) + 1):
        for j in range(1, total_days + 1):
            if j >= duration[i - 1]:
                # 如果j天足够访问景点i,则考虑访问或不访问景点i
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - duration[i - 1]] + scores[i - 1])
            else:
                # 如果j天不足以访问景点i,则不访问景点i
                dp[i][j] = dp[i - 1][j]

    # 从dp数组中找出最大评分
    max_score = dp[len(duration)][total_days]

    # 找出访问哪些景点可以获得最大评分
    selected_spots = []
    j = total_days
    for i in range(len(duration), 0, -1):
        if dp[i][j] != dp[i - 1][j]:
            selected_spots.append(i)
            j -= duration[i - 1]

    selected_spots.reverse()
    return max_score, selected_spots

# 景点的持续时间和评分
duration = [1, 2, 3, 1]
scores = [7, 8, 9, 6]

# 总时间限制
total_days = 4

# 计算最大价值和选择的景点
max_score, selected_spots = optimize_tour(total_days, duration, scores)
print("最大价值:", max_score)
print("选择的景点编号:", selected_spots)