Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 2015-03-19 05:11  Tonix  阅读(275)  评论(0编辑  收藏  举报