def knapsack(max_weight, weights, values):
n = len(values)
# Initialize the DP table
dp = [[0 for _ in range(max_weight + 1)] for _ in range(n + 1)]
# Fill the DP table
for i in range(1, n + 1):
for w in range(1, max_weight + 1):
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], values[i-1] + dp[i-1][w-weights[i-1]])
else:
dp[i][w] = dp[i-1][w]
return dp[n][max_weight]
# Example usage
weights = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
values = [60, 100, 120, 140, 160, 180, 200, 220, 240, 260]
max_weight = 100
result = knapsack(max_weight, weights, values)
print("Maximum value that can be obtained:", result)
Python:0-1背包问题
最新推荐文章于 2024-08-28 21:25:50 发布