动态规划—北大POJ Charm Bracelet(01背包问题)

                                                                Charm Bracelet

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

题目大意:已知背包最大容纳的重量、各物品的重量和物品的价值,将物品装入背包里,使包里的总价值达到最大

题目思路:用动态规划求解,这道题是学习动态规划的最好的、也是最基础的题目

AC代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int f[14000];       //注意数组要开的足够大才可以,否则WA
int w[3500],d[3500];
int max(int a,int b)  //用了求最大值
{
 if(a>=b)
  return a;
 else
  return b;
}
int dp(int n,int m)
{
    int i,j;
    memset(f,0,sizeof(f));
    memset(w,0,sizeof(w));
 memset(d,0,sizeof(d));

    for(i=1;i<=n;i++)     //输入每个物品的重量和价值
    scanf("%d%d",&w[i],&d[i]);
   
    for(i=1;i<=n;i++)    //外层for循环用来控制要装入的物品的重量
    {
    for(j=m;j>=w[i];j--)  //内层for循环用来控制是否要装入该物品,如果j>=w[i]就先假设把它装进去,否则无法装入
    {
    f[j]=max(f[j-w[i]]+d[i],f[j]);  //假设装入物品,而且比不装时价值大时才将它装入,否则不将物品装入
    }
    }
    return f[m];      //f[m]表示背包装满时的价值,也是最大值
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)  //输入物品总数和背包的最大容量
    {
     printf("%d\n",dp(n,m));
 } 
 return 0;
}
     
关键点:可以先通过二维数组进行理解,但是用二维数组的坏处是:数组开太大会超内存,太小时WA,所以最后要将它转换成一维数组

解题体会:动态规划真不好学啊,还是没有掌握到动态规划的精髓,还要继续努力啊大哭奋斗

解题时间:2014年8月1日


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值