Charm Bracelet POJ - 3624 (0 1背包问题)

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

题意:

在重量不超过M的条件下,计算评级的最大可能总和。

思路:

计算最大可能总和当然要选取重量小且评级高且重量能尽可能接近背包所能承受重量。例如样例所给数据: 首先使重量不大于6,选取重量分别为1 2 3 的三种,有两个重量都为2,选择评级更高的,所以我们最终计算得到的评级最大可能总和为4+7+12=23.下面的代码时用一维数组写的

代码:

#include<stdio.h>
#include<algorithm>
using namespace std;
int f[13000],W[4000],D[4000];      //f数组表示重量为j的最高评级
int main()
{
    int n,m,i,j;
    scanf("%d %d",&n,&m);
    for(i=1; i<=n; i++)
        scanf("%d %d",&W[i],&D[i]);
    for(i=1; i<=n; i++)
        for(j=m; j>=W[i]; j--)     //用一维数组循环要从最大值开始
        {
            f[j]=max(f[j],f[j-W[i]]+D[i]);
        }
    printf("%d\n",f[m]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Piink/article/details/105522094
今日推荐