动态规划—北大POJ Charm Bracelet(01背包问题)
来源:互联网 发布:上海市行知实验中学 编辑:程序博客网 时间:2024/06/08 08:13
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 theN (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weightWi (1 ≤ Wi ≤ 400), a 'desirability' factorDi (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more thanM (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 61 42 63 122 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日
- 动态规划—北大POJ Charm Bracelet(01背包问题)
- POJ 3624 Charm Bracelet 动态规划(01背包问题)
- POJ 题目3624 Charm Bracelet(动态规划 01背包)
- poj 3624 Charm Bracelet 01背包问题
- POJ 3624 Charm Bracelet 01背包问题
- 01背包问题:poj 3624 Charm Bracelet
- POJ 3624Charm Bracelet (01背包问题)
- POJ 3624 Charm Bracelet(01背包问题)
- Charm Bracelet poj 3624 (01) 背包问题 c++
- POJ 3624 Charm Bracelet(01背包问题)
- 0-1背包问题,poj 3624 Charm Bracelet动态规划-解题报告,增加最优路径构建
- poj 3624 Charm Bracelet (01背包)
- poj 3624 Charm Bracelet(01背包)
- 【POJ-3624】Charm Bracelet (01背包)
- POJ 3624 Charm Bracelet(01背包)
- POJ 3624 Charm Bracelet (01背包)
- 【POJ】3624 - Charm Bracelet(01背包)
- POJ 3624 Charm Bracelet(01背包)
- 以XML的方式保存密码
- Resin#unexpected end of file in utf8 character解决过程
- Subsets
- 简单的HTML中常用的一些特效方法
- UVA10720- Graph Construction
- 动态规划—北大POJ Charm Bracelet(01背包问题)
- 对于Mahout__"推荐算法"的初步认识(2)
- OC创建类和对象 设置器和存储器
- unix网络编程卷2的头文件unpipc.h下载和编译(转)
- 自动运行war的plugin
- 8.jQuery 基础事件
- C++中模板特化的概念
- 八月的我。。。
- hdu 4609 3-idiots 【FFT快速傅立叶变换】