最新消息:点击查看大S的省钱秘笈

POJ 3624 Charm Bracelet C++版

POJ题解 Slyar 124浏览 0评论

文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

DP 01背包

Description

Bessie has gone to the mall's jewelry store and spies a charm bracelet. Of course, she'd like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weight Wi (1 ≤ Wi ≤ 400), a 'desirability' factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880).

Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings.

Input

* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di

Output

* Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints

Sample Input

4 6
1 4
2 6
3 12
2 7

Sample Output

23

Slyar:标准的01背包,动态转移方程如下。其中dp[i,j]表示的是前i个物品装入容量为j的背包里所能产生的最大价值,w[i]是第i个物品的重量,d[i]是第i个物品的价值。如果某物品超过背包容量,则该物品一定不放入背包,问题变为剩余i-1个物品装入容量为j的背包所能产生的最大价值;否则该物品装入背包,问题变为剩余i-1个物品装入容量为j-w[i]的背包所能产生的最大价值加上物品i的价值d[i]...恩,多清晰...

还有一点是,这题我之前使用二维数组做的,不过提交之后MLE了...所以只能想办法使用一维数组,手工模拟一下发现dp[i,j]只跟之前的某几个值有关,再之前计算的结果就都没用了...所以我们就可以用一个数组来重复使用了,不过注意要倒序,保证无后效性...

if (w[i]>j) dp[i,j] = dp[i-1,j]

else dp[i,j] = max(dp[i-1,j-w[i]]+d[i],dp[i-1,j])

所能产生的最大价值

转载请注明:Slyar Home » POJ 3624 Charm Bracelet C++版

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. 请教下: for (int j = m; j >= w[i]; j--) { dp[j] = max(dp[j-w[i]] + d[i], dp[j]); } 这个循环中为什么j不从小到大呢
    匿名5年前 (2012-05-15)回复