标签:maximum lan cto har ati space limit logs 一个
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 iin 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.
4 6
1 4
2 6
3 12
2 7
23
///01背包问题 #include <iostream> using namespace std; int d[3403];//‘desirability‘ int w[3403];//重量 int dp[3403][12881];//dp[i][j],i表示拿前i件,j表示总重不能超过j int main() { int n,m;//n:项链件数,m:不能超过的重量 cin>>n>>m; for(int i=1;i<=n;i++){ cin>>w[i]>>d[i]; } //为边界赋值,拿前1件的情况 if(w[1]<m){ dp[1][m]=w[1]; } else{ dp[1][m]=0; } int i,j; for(i=1;i<=n;i++){ for(j=0;j<=m;j++){ if(j<w[i]){ dp[i][j]=dp[i-1][j]; } else{ dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+d[i]); } } } cout<<dp[n][m]<<endl; return 0; }
我还写了个,滚动数组的写法,可是在一个大数的测试WA了/(ㄒoㄒ)/~~,各位给看看哪里错了,或者贴个滚动数组的写法,欢迎交流,感激不尽。
///01背包问题,滚动数组 #include <iostream> using namespace std; int d[3403];//‘desirability‘ int w[3403];//重量 int dp[1288071];//dp[i][j],i表示拿前i件,j表示总重不能超过j int main() { int n,m;//n:项链件数,m:不能超过的重量 cin>>n>>m; for(int i=1;i<=n;i++){ cin>>w[i]>>d[i]; } //为边界赋值,拿前1件的情况 if(w[1]<m){ dp[1]=w[1]; } else{ dp[1]=0; } for(int i=0;i<=n;i++){ for(int j=m;j>=w[i];j--){ dp[j]=max(dp[j],dp[j-w[i]]+d[i]); } } cout<<dp[m]<<endl; return 0; }
标签:maximum lan cto har ati space limit logs 一个
原文地址:http://www.cnblogs.com/LuRenJiang/p/7399344.html