Charm Bracelet (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
题目大意:这是一道裸01背包问题,没什么花样,可以当模板题来看。 Bessie去商场买珠宝,她要往手链上镶嵌珠宝,但是有重量限制,每块珠宝有两个属性,重量,价值(珠宝不可切割),问在重量不超额的情况下,价值最高多少。

01背包 属于是贪心中的一个分支,个人认为01背包关键在于状态的保存和更新,即dp【i】的更新。

01背包 01就是指该件物品仅有一件舍或是取(0 or 1)属于背包问题中比较简单的一类,就01背包来讲,有两种方法可解,一维背包和二维背包。


一维状态转移方程(val价值,weight重量,w最大承重,n物品件数)

    forint i=1;i<=n;i++for(int j=v;j>=weight[i];j--)//这里是关键点,一定要逆序
            dp[j]=max(dp[j],dp[j-wegiht[i]]+val[i]);
二维状态转移方程(变量同一维)
  dp[i][v]= max(dp[i-1][v], dp[i-1][v-weight[i]]+val[i]); 

就这道题,我是用一维过的

代码贴出来

复制代码
 1 #include <iostream>
 2 #include<stdio.h>
 3 #include<math.h>
 4 #include<string.h>
 5 #include<algorithm>
 6 #include<ctype.h>
 7 #include<stdlib.h>
 8 #include<vector>
 9 #include<queue>
10 using namespace std;
11 #define oo 0x3f3f3f3f
12 #define maxn 20010
13 
14 int dp[maxn],weight[maxn],val[maxn];
15 
16 void Init()
17 {
18     memset(dp,0,sizeof(dp));
19     memset(val,0,sizeof(val));
20     memset(weight,0,sizeof(weight));
21 }
22 
23 int main()
24 {
25     int n,w;
26     while(scanf("%d%d",&n,&w)!=EOF)
27     {
28         Init();
29         for(int i=1;i<=n;i++)
30         {
31             scanf("%d%d",&weight[i],&val[i]);
32         }
33         for(int i=1;i<=n;i++)
34             for(int j=w;j>=weight[i];j--)
35         {
36             dp[j]=max(dp[j],dp[j-weight[i]]+val[i]);
37         }
38         printf("%d\n",dp[w]);
39     }
40     return 0;
41 }
复制代码

 




posted on   就想起个能用的名字  阅读(171)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示