总时间限制: 1000ms 内存限制: 65536kB

描述

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 _W(1 ≤ W≤ 400), a ‘desirability’ factor D(1 ≤ D≤ 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.

输入

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

输出

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

样例输入

  1. 4 6
  2. 1 4
  3. 2 6
  4. 3 12
  5. 2 7

样例输出

  1. 23

思路

F[i][j]表示前 i 种物品, 使它们总重量不超过 j 的最优取法取得的价值总和.
题目要求F[N][M].

边界条件

  1. if( w[1] <= j )
  2. F[1][j] = d[1];
  3. else
  4. F[1][j] = 0;

如果第1种物品的重量小于j, 我们就把它塞进背包, 价值总和为d[1].

否则, 我们不拿第1种物品.

递推公式

  1. F[i][j] = max( F[i-1][j], F[i-1][ j-w[i] ]+d[i] );

到了第i种物品, 我们可以要它也可以不要它.

  • 如果不要第 i 种物品, 我们则要在第 i-1 种物品里凑出重量不超过 j 的拿法.
  • 如果要第 i 种物品, 我们则在第 i-1 种物品里凑出重量为 j-w[i] 的拿法, 再加上第 i 种物品的价值d[i].

代码

  1. #include <iostream>
  2. #include <cstring>
  3. #include <algorithm>
  4. using namespace std;
  5. int dp[30000];
  6. int N, M;
  7. typedef struct Bracelet {
  8. int weight;
  9. int desirability;
  10. }Bracelet;
  11. int main() {
  12. /* Read data and initialize */
  13. cin >> N >> M;
  14. Bracelet* obj = new Bracelet[M+4];
  15. for(int i = 1; i <= N; i++) {
  16. cin >> obj[i].weight >> obj[i].desirability;
  17. }
  18. memset(dp, 0x0, sizeof(dp));
  19. /* Compute function */
  20. for(int i = 1; i <= N; i++) {
  21. for(int j = M; j >= obj[i].weight; j--) {
  22. dp[j] = max( dp[j],
  23. dp[j-obj[i].weight] + obj[i].desirability );
  24. }
  25. }
  26. /* Display result */
  27. cout << dp[M] << endl;
  28. delete[] obj;
  29. return 0;
  30. }