Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 45540 | Accepted: 19429 |
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 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.
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
Source
题目意思:有N件物品放入容积为M的背包,每个物品所占的体系为W[i],价值为D[i],使得价值最大
动态规划,用F[i][j]表示放入前i个商品,使得容积为j的价值最大的最大价值
边界条件为
if w[1]<j
F[1][j]=d[1];
else F[1][j]=0;
F[i][j]=max[F[i-1][j],F[i-1][j-w[i]]+D[i];
没有优化的二维代码如下
#include <stdio.h> #include <string.h> #include <string> #include <iostream> using namespace std; #define max(a,b) a>b?a:b; //数组要设的比给的范围稍大一些 int dp[3410][12900]; int path[3410][12900]; int w[3410]; int d[3410]; int totalN; int totalW; int main() { int i,j; scanf("%d",&totalN); scanf("%d",&totalW); for(i=1;i<=totalN;i++) { scanf("%d",&w[i]); scanf("%d",&d[i]); } memset(dp,0,sizeof(dp)); for(i=1;i<=totalN;i++){ for(j=1;j<=totalW;j++){ dp[i][j] = dp[i-1][j]; if(j>=w[i] && dp[i][j]<dp[i-1][j-w[i]]+d[i]){ dp[i][j] =dp[i-1][j-w[i]]+d[i]; //path[i][j] = 1; } } } printf("%d\n",dp[totalN][totalW]); return 0; }优化逆序计算容积j,还可以用一维数组优化