Descriptioncss
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).jquery
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.ios
Inputweb
* 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 Inputui
4 6 1 4 2 6 3 12 2 7
Sample Outputurl
23
背包问题:spa
#include"stdafx.h"
#include<iostream>
usingnamespacestd;
#defineMAXSIZE1000
intf[MAXSIZE+1],c[MAXSIZE+1],w[MAXSIZE+1];
int_main(intargc,_TCHAR*argv[])
{
intN,V;
cin>>N>>V;
inti=1;
for
(;i<=N;++i)
{
cin>>c[i]>>w[i];
}
for
(i=1;i<=N;++i)
{
for
(intv=V;v>=c[i];--v)
//c[i]可优化为bound,bound=max{V-sumc[i,...n],c[i]}
{
f[v]=(f[v]>f[v-c[i]]+w[i])?f[v]:f[v-c[i]]+w[i];
}
}
//当i=N时,能够跳出循环单独计算F[V]
cout<<f[V]<<
'\n'
;
system
(
"pause"
);
return0;
}
#include<stdio.h> //#include<string.h> int d[1300]; int w[400],v[100]; int main() { int n,m,i,j; //memset(d,0,seizeof(d)); scanf("%d %d",&n,&m); for(i=1;i<=n;i++) scanf("%d %d",&w[i],&v[i]); for(i=1;i<=n;i++) for(j=m;j>=w[i];j--) d[j]=(d[j]>d[j-w[i]]+v[i])?d[j]:d[j-w[i]]+v[i]; printf("%d\n",d[m]); return 0; }
1)0-1背包问题和 零碎背包问题是不一样的,前者只能用动态规划来作, 后者能够用贪心算法。
2)动态规划的核心是 “有多个重叠子问题”,“自底向上”解决问题。
3) 0-1背包问题 ,W为最大重量,n为物体个数,求最大的价值Value,可在O(nW)的时间复杂度内解算出来。
这个题目是经典的0-1背包问题,借此学习0- 1背包