百练 01 Charm Bracelet

来源:互联网 发布:org.apache.http.util 编辑:程序博客网 时间:2024/06/03 19:24

百练 01 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(1N3,402) available charms. Each charm iin the supplied list has a weight Wi(1Wi400), a ‘desirability’ factor Di(1Di100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M(1M12,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

刷表法

#include <iostream>#include <algorithm>using namespace std;const int MAX_NUM = 3402 + 5;const int MAX_WEIGHT = 12880 + 5;// N个饰品,M为重量限制int N, M;// 每个饰品的重量int W[MAX_NUM];// 每个饰品的价值int D[MAX_NUM];// dp(i,j)表示前i个饰品,最大重量为j的状态下的最大价值int dp[MAX_WEIGHT];int main() {    cin >> N >> M;    for(int i = 1; i <= N; i++) {        cin >> W[i] >> D[i];    }    // 边界    for(int j = 0; j <= M; j++) {        dp[j] = 0;    }    for(int i = 1; i <= N; i++) {        for(int j = M; j >= 0; j--) {            if(j >= W[i]) {                dp[j] = max(dp[j], dp[j - W[i]] + D[i]);            }        }    }    cout << dp[M] << endl;    return 0;}

边输入边处理

#include <iostream>#include <algorithm>using namespace std;const int MAX_NUM = 3402 + 5;const int MAX_WEIGHT = 12880 + 5;// N个饰品,M为重量限制int N, M;// 每个饰品的重量int W;// 每个饰品的价值int D;// dp(i,j)表示前i个饰品,最大重量为j的状态下的最大价值int dp[MAX_WEIGHT];int main() {    cin >> N >> M;    // 边界    for(int j = 0; j <= M; j++) {        dp[j] = 0;    }    for(int i = 1; i <= N; i++) {        cin >> W >> D;        for(int j = M; j >= 0; j--) {            if(j >= W) {                dp[j] = max(dp[j], dp[j - W] + D);            }        }    }    cout << dp[M] << endl;    return 0;}
0 0