Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  502 随笔 :: 0 文章 :: 3 评论 :: 11万 阅读
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

Very good problem to learn knapsack (complete knapsack in this case).

My brutal-force solution in Python got AC too, which surprised me a bit. Here is the ideal DP solution. Just check comments:

复制代码
T = int(input())
for _ in range(0, T):
    n, k = map(int, input().strip().split())
    arr = [int(i) for i in input().strip().split()]

    dp = [0] * (k + 1)
    arr.sort()
    for g in range(1, k + 1):     # k slots in knapsack
        for i in range(0, n):    # for each candidate
            if arr[i] <= g:                
                # each item, cost == gain
                dp[g] = max(dp[g], arr[i] + dp[g - arr[i]])
    print (dp[k])
复制代码
posted on   Tonix  阅读(278)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示