Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17111 | Accepted: 7741 |
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
Source
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
const int maxm = 12881;
const int maxn = 3403;
int dp[maxn][maxm];
int main()
{
freopen("in.txt","r",stdin);
int n,m,w,d;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&w,&d);
for(int j=m;j>0;j--)
{
if(j>=w)
dp[i][j]=max(dp[i-1][j],dp[i-1][j-w]+d);
else
dp[i][j]=dp[i-1][j];
}
}
printf("%d\n", dp[n][m]);
}
上面的代码会MLE,这一题很抠内存,所以应该用滚动数组优化一下。
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
const int maxm = 12881;
int dp[maxm];
int main()
{
freopen("in.txt","r",stdin);
int n,m;
int w,d;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&w,&d);
for(int j=m;j>=w;j--)
dp[j]=max(dp[j-w]+d,dp[j]);
}
printf("%d\n", dp[m]);
}
这里的dp数组时
从上到下、从右到左计算的。在计算dp(i,j)之前,dp[j]保存的就是dp(i-1,j)的值,而dp[j-w]里保存的是dp(i-1,j-w)。这样,dp[j]=max(dp[j-w]+d,dp[j])实际上是把max(
dp(i-1,j),dp(i-1,j-w)+d)保存在dp[j]中,覆盖掉dp[j]原来的dp(i-1,j)。