首页 > 其他 > 详细

HackerRank - Knapsack

时间:2015-03-19 06:17:31      阅读:534      评论:0      收藏:0      [点我收藏+]

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])

HackerRank - Knapsack

原文:http://www.cnblogs.com/tonix/p/4349273.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!