编辑代码

def optimize_fruit_bag(weights, values, weight_limit):
    n = len(weights)
    dp = [[0] * (weight_limit + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(1, weight_limit + 1):
            if weights[i - 1] <= j:
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1])
            else:
                dp[i][j] = dp[i - 1][j]

    result = []
    i, j = n, weight_limit
    while i > 0 and j > 0:
        if dp[i][j] != dp[i - 1][j]:
            result.append(i - 1)
            j -= weights[i - 1]
        i -= 1

    return result

def main():
    weights = [15, 18, 10, 9]
    values = [300, 180, 150, 270]
    weight_limit = 20
    selected_indices = optimize_fruit_bag(weights, values, weight_limit)
    print("Selected fruits to maximize value:")
    for index in selected_indices:
        print(f"Fruit {index + 1} - Weight: {weights[index]} kg, Value: {values[index]}")

if __name__ == "__main__":
    main()