poj 4131:Charm Bracelet 動規

題目

總時間限制: 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,求價值最大。可以考慮某一個物品是否選中的最大值,即

  1. 該物品選中:該物品的價值加上剩下N-1個物品的最大價值
  2. 該物品沒選中:剩下N-1個物品的最大價值。

其中,第一種需要考慮剩下N-1種物品的限重也是減小的。

遞推公式:V_MAX[i,j]=MAX(V_MAX[i1,j],V_MAX[i1,jw[i]]+d[i])V\_MAX[i,j] = MAX(V\_MAX[i-1,j],V\_MAX[i-1,j-w[i]]+d[i]) ,其中V_MAX[i,j]V\_MAX[i,j]是第一i物品限重爲j時的最大值,w[i]w[i]是第i個物品的質量 ,d[i]d[i]是第i個物品的價值。V_MAX[i1,j]V\_MAX[i-1,j]是不選第i個物品,價值爲前i1i-1個限重爲jj時的價值;V_MAX[i1,jw[i]]+d[i]V\_MAX[i-1,j-w[i]]+d[i]是選第ii個物品限重爲jj的價值,這裏是減是因爲限重是已經固定的,所以只能是調整前i1i-1個物品的質量,如果是加的話,限重就不是jj

該題由於數組太大,內存限制會超,故使用滾動數組記錄,只保留一個一維數組來記錄

#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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章