标签:
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背包主要关系:
if (dp[j]<dp[j-w[i]]+d[i])
dp[j]=dp[j-w[i]]+d[i];
对于题给的例子:
1 2 3 2
dp[1] 4 4 4 4
dp[2] 4 6 6 7
dp[3] 4 10 12 12
dp[4] 4 10 16 13
dp[5] 4 10 18 19
dp[6] 4 10 22 23
dp[j]表示容量为j时能放的最多东西。从1到n个物品一个一个的放和比较。
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 int main() 5 { 6 int w[3500],d[3500],n,m,i,j,dp[13500]; 7 while (~scanf("%d%d",&n,&m)) 8 { 9 memset(dp,0,sizeof(dp)); 10 for (i=1;i<=n;i++) scanf("%d%d",&w[i],&d[i]); 11 for (i=1;i<=n;i++) 12 { 13 for (j=m;j>=w[i];j--) 14 if (dp[j]<dp[j-w[i]]+d[i]) 15 dp[j]=dp[j-w[i]]+d[i]; 16 } 17 printf("%d\n",dp[m]); 18 } 19 }
POJ 3624 Charm Bracelet (01)(背包入门)
标签:
原文地址:http://www.cnblogs.com/pblr/p/4757096.html