摘要
-01背包类型 使用状态压缩 为一维数组 节省空间 进行dp
原题目摘要
-Charm Bracelet
-
-
描述
-
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.
输入
-
Line 1: Two space-separated integers: N and M
Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: W i and D i
输出
- Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints 样例输入
-
4 6 1 4 2 6 3 12 2 7
样例输出
-
23
来源
- USACO 2007 December Silver
题目理解
-01背包模型 不超过m的条件下的最大结果。
最开始直接使用二维数组进行递归 设置状态dp[i][m]:不超过m的情况下的最大值,dp[i][m]=max(dp[i-1][m],dp[-1][m-w[i]]+d[i]); 可是m远远大于i造成极度的浪费 后思考使用一维数组进行递推。
dp[j] 为i情况选的最大值;dp[j]>=w[i]的情况下可以再增加 反之则只能是不选择i使用上一次的数据;
for(int i=1;i<n;i++){
for(int j=m;j>=w[i];j--){
dp[j] =max(dp[j],dp[j-w[i]]+d[i]) ;
}
}
注意
-
因为更新数据需要用到上一轮前面的数据 所以j的方向是从m到w[i];
日期
-2017 08 26
附加
-
代码
-
#include <algorithm>
#include <iostream>
#include <memory>
#include <cstdio>
using namespace std;
#define MAX 20004
int n;
int d[MAX],w[MAX];
int dp[MAX];
int m;
void solve(){
//edge condition
for(int j=0;j<=m;j++){
if(j>=w[0]) dp[j]=d[0];
}
//i个之前的最大值
for(int i=1;i<n;i++){
for(int j=m;j>=w[i];j--){
dp[j] =max(dp[j],dp[j-w[i]]+d[i]) ;
}
}
}
int main(){
scanf("%d%d",&n,&m);
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++){
scanf("%d%d",&w[i],&d[i]);
}
solve();
printf("%d\n",dp[m]);
return 0;
}