题目来源:http://poj.org/problem?id=3624
3624:CharmBracelet
总时间限制: 1000ms 内存限制: 65536kB
Description
Bessie has gone to the mall's jewelry store and spies a charmbracelet. Of course, she'd like to fill it with the best charms possible fromthe N (1 ≤ N ≤ 3,402) available charms. Eachcharm 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. Bessiecan 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 charmswith their weights and desirability rating, deduce the maximum possible sum ofratings.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Line i+1 describes charm i withtwo space-separated integers: Wi and Di
Output
* Line 1: A single integer that is the greatest sum of charmdesirabilities that can be achieved given the weight constraints
Sample Input
4 6
1 4
2 6
3 12
2 7
SampleOutput
23
-----------------------------------------------------
解题思路
0-1背包问题:动态规划
递推表达式:
DP[n][m]表示有n件物品,背包容量W为m时的最大化收益R
DP[n][m] = max(DP[n-1][m-w[n]] + r[n]), DP[n-1][m])
max里的第一项表示放入第n件物品,m表示不放入
由于每次递推只用到第n-1行和第n行,所以只需用一个数组存储一行
这是递推表达式变为:
DP[m] = max ( DP[m-w[n]]+ r[n], DP[m])
由于第n行的结果对第n-1行是覆盖写入,故循环时要从大往小了循环,否则会造成用第n行的结果更新第n行的结果,物理意义是将一个物品放入背包多次。
核心代码
memset(dp, 0, (m+1)*sizeof(int)); // 初始化
for (i=0; i<n; i++) // 对于每一件物品
{
for (j=m; j>=w[i]; j--) // 倒着算保证每件物品只被放一次
{
dp[j] = max(dp[j-w[i]] + d[i], dp[j]); // 降维的递推表达式
}
}
cout << dp[m];
-----------------------------------------------------
代码
#include<fstream>
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
ifstream fin("poj3624.txt");
int n,m,i,j;
fin >> n >> m;
int* w = new int[n];
int* d = new int[n];
for (i=0; i<n; i++)
{
fin >> w[i] >> d[i];
}
fin.close();
int *dp = new int[m+1]; // 动态规划一维数组
// 递推式:dp[n][w] = max( dp[n-1][w-w[n]] + d[n], dp[n-1][w] )
memset(dp, 0, (m+1)*sizeof(int)); // 初始化
for (i=0; i<n; i++) // 对于每一件物品
{
for (j=m; j>=w[i]; j--) // 倒着算保证每件物品只被放一次
{
dp[j] = max(dp[j-w[i]] + d[i], dp[j]); // 降维的递推表达式
}
}
cout << dp[m];
delete[] w;
delete[] d;
delete[] dp;
return 0;
#endif
#ifdef ONLINE_JUDGE
int n,m,i,j;
cin >> n >> m;
int* w = new int[n];
int* d = new int[n];
for (i=0; i<n; i++)
{
cin >> w[i] >> d[i];
}
int *dp = new int[m+1]; // 动态规划一维数组
// 递推式:dp[n][w] = max( dp[n-1][w-w[n]] + d[n], dp[n-1][w] )
memset(dp, 0, (m+1)*sizeof(int)); // 初始化
for (i=0; i<n; i++) // 对于每一件物品
{
for (j=m; j>=w[i]; j--) // 倒着算保证每件物品只被放一次
{
dp[j] = max(dp[j-w[i]] + d[i], dp[j]); // 降维的递推表达式
}
}
cout << dp[m];
delete[] w;
delete[] d;
delete[] dp;
return 0;
#endif
}