总时间限制: 1000ms 内存限制: 65536kB
描述
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: Wi and Di
输出
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
简单的01背包问题
但通过平常的动态规划无法解决,因为题目数据范围 n * m 过大,会导致MLE,所以需要利用滚动数组解决问题。
再来讨论一下状态转移方程
说状态转移方程是因为我觉得,这样真的好理解,杰哥别骂我
对于平常的动态规划思路,我们用dp[i][j] 来表示对于前 i 个物品,使用 j 重量所能获得的最大价值,而它的取值有两种情况
取走第 i 个物品 此时dp [ i ] [ j ] = dp[ i - 1 ] [ j - a[ i ].w ] + a[i].p
不取第 i 个物品 此时dp [ i ] [ j ] = dp[ i - 1 ] [ j ]
dp [ i ] [ j ]应为上述两式中最大值, 即,
当 j >= a[i].w 时,
dp[ i ] [ j ] = max(dp[ i - 1 ] [ j ], dp[ i - 1 ] [ j - a[ i ].w ] + a[i].p)
那么就可以轻松据此写出动态规划代码啦,我太懒了就不贴出来了
可是对于这一题需要滚动数组
前面说过因为数据量的原因,二维数组的存储方式会MLE,那么是否可以尝试一维数组存储呢?
可以发现,在二维数组中,对于每个dp [ i ] [ j ], 他的值只取决于正上方的第一个行元素,那么就可以使用一个一维数组不断更新来实现一维存储啦。当然更新时要注意每一行从后往前更新,因为如果从左往右更新,对于第 j 个元素, 前 j 个元素已经更新过了, 可事实上它需要的是未更新过的前 j - 1个数据的值来更新其本身的值。
最后到了懒鬼们最爱的 贴代码环节。
#include<iostream>
#include<algorithm>
using namespace std;
int m, dp[13000];
struct thing
{
int w;
int p;
};
thing a[3500];
int main()
{
int n;
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i].w >> a[i].p;
for (int i = 1; i <= n; i++)//从第一行向下,一行行更新
for (int j = m; j > 0; j--)//从后往前更新
if(j >= a[i].w) dp[j] = max(dp[j], dp[j - a[i].w] + a[i].p);
cout << dp[m];
return 0;
}