題目
總時間限制: 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
思路
動規題目,首先找到子問題。要解決的問題是N個物品,限重M,求價值最大。可以考慮某一個物品是否選中的最大值,即
- 該物品選中:該物品的價值加上剩下N-1個物品的最大價值
- 該物品沒選中:剩下N-1個物品的最大價值。
其中,第一種需要考慮剩下N-1種物品的限重也是減小的。
遞推公式: ,其中是第一i物品限重爲j時的最大值,是第i個物品的質量 ,是第i個物品的價值。是不選第i個物品,價值爲前個限重爲時的價值;是選第個物品限重爲的價值,這裏是減是因爲限重是已經固定的,所以只能是調整前個物品的質量,如果是加的話,限重就不是了
該題由於數組太大,內存限制會超,故使用滾動數組記錄,只保留一個一維數組來記錄
#include <stdio.h>
#include<algorithm>
int N,M;
int w[3405];
int d[3405];
int lo[12880];
using namespace std;
int main()
{
scanf("%d%d",&N,&M);
for(int i=0;i<N;i++){
scanf("%d%d",&(w[i]),&(d[i]));
}
for(int i=0;i<N;i++){
for(int j=M;j>=w[i];j--){
lo[j] = max(lo[j],lo[j-w[i]]+d[i]);
}
}
printf("%d",lo[M]);
return 0;
}