01背包 实例
2009-11-23 22:25
197 查看
01背包实例
看了并理解了dd大牛写的背包九讲中的01背包,然后看了poj上面的3624这道题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 weightWi (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
抽象一下题意就是:有N件大小和价值都可能不同的物品,放入容量为M的容器中,求解所能达到的最大价值。
首先是确定基本思路即状态转移方程
f[v]=max{f[v],f[v-c[i]]+w[i]};(这个是优化了空间之后的转移方程)
背包问题的主要解题思路就是状态转移了,从而优化时间和空间
在输入某件物品后就要依次确定这件物品是否要放入容量为V到c的背包
当判断是否要把某件物品放入容量为j的背包中时只需把不把这件物品放入时的总价值与容量为j-c的背包所能达到的最大价值加上这件物品的价值比较,那么此时容量为j的背包所能达到的最大价值就是这两者的大者。
在具体写代码时还可以优化下时间
++++++++++++++++++++++++
#include<stdio.h>
#define max(a,b) a>b?a:b
main()
{
int f[3403]={0};
int N,V,c,w,i,j;
scanf("%d %d",&N,&V);
for(i=0;i<N;i++)
{
scanf("%d %d",&c,&w);
for(j=V;j>=c;j--)
{
f[j]=max(f[j],f[j-c]+w);
}
}
printf("%d/n",f[V]);
}
++++++++++++++++++++++++
相关文章推荐
- 动态规划实例(七):01背包问题最大价值
- DP实例之01背包问题C语言实现
- 01背包问题
- 01背包初始化的细节问题与循环下限的改进
- ModelAndView实例01
- 01背包-动态规划
- nyoj860又见01背包
- HDU-CRB and His Birthday(动态规划本质未认清)---01背包与完全背包的结合!
- 01背包问题
- 九度OJ 1025:最大报销额 (01背包、DP)
- 背包之01背包、完全背包、多重背包详解
- 又见01背包
- HDU-2159 FATE,01背包变形
- HDU 2955 Robberies……(01背包 + dp存储成功概率(转化),下标存储抢到多少钱,输出下标)
- UESTC1133 菲波拉契数制 01背包思想
- 种类数,方案划分,01背包
- nyoj 又见01背包
- 动态规划(01背包、完全背包、多重部分和、LCS、LIS、划分数、多重集组合数)
- HDU - 2955 Robberies 01背包
- 01背包问题的java界面实现