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揹包