# 3624：CharmBracelet

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表示不放入

DP[m] = max ( DP[m-w[n]]+ r[n], DP[m])

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
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120