# POJ 3624 Charm Bracelet C++版

OJ题解 5417浏览

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]...恩，多清晰...

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

### 网友最新评论 (1)

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