文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
DP 01背包
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
Slyar:标准的01背包,动态转移方程如下。其中dp[i,j]表示的是前i个物品装入容量为j的背包里所能产生的最大价值,w[i]是第i个物品的重量,d[i]是第i个物品的价值。如果某物品超过背包容量,则该物品一定不放入背包,问题变为剩余i-1个物品装入容量为j的背包所能产生的最大价值;否则该物品装入背包,问题变为剩余i-1个物品装入容量为j-w[i]的背包所能产生的最大价值加上物品i的价值d[i]...恩,多清晰...
还有一点是,这题我之前使用二维数组做的,不过提交之后MLE了...所以只能想办法使用一维数组,手工模拟一下发现dp[i,j]只跟之前的某几个值有关,再之前计算的结果就都没用了...所以我们就可以用一个数组来重复使用了,不过注意要倒序,保证无后效性...
if (w[i]>j) dp[i,j] = dp[i-1,j]
else dp[i,j] = max(dp[i-1,j-w[i]]+d[i],dp[i-1,j])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; const int N = 3403; const int M = 12881; int dp[M] = {0}; int max(int x, int y) { return x > y ? x : y; } int main() { int n, m; int w[N], d[M]; cin >> n >> m; for (int i = 1; i <= n; i++) { cin >> w[i] >> d[i]; } for (int i = 1; i <= n; i++) { for (int j = m; j >= w[i]; j--) { dp[j] = max(dp[j-w[i]] + d[i], dp[j]); } } cout << dp[m] << endl; return 0; } |