4131:Charm Bracelet,考点:动规,滚动数组节省空间

原题:http://bailian.openjudge.cn/practice/4131/

描述

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.

(这么长的英文我也懒得看)

有N见物品和一个容积为M的背包,第i件物品的重量w[i],价值为d[i],求解将哪些物品放入背包可使价值总和最大,每种物品只有一件,可以选择放或者不放。

输入

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

解法

思路:如果直接动态规划,按照背包问题的一般解法,用二维数组来存,会MLE

代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int weight[3505];
int value[3505];
int dp[3505][13005];//dp[i][j]:考虑前i种物品,容积为j时的最大价值
int main()
{
    memset(dp, 0, sizeof(dp));
    int N, M;
    cin >> N >> M;
    for (int i = 0; i < N; i++)
        cin >> weight[i] >> value[i];
    for (int j = 0; j <= M; j++) {
        if (j >= weight[0])
            dp[0][j] = value[0];
    }
    for (int i = 1; i < N; i++) {
        for (int j = 0; j <= M; j++) {
            dp[i][j] = dp[i - 1][j];
            if (j >= weight[i]) {
                dp[i][j] = max(dp[i][j], dp[i - 1][j - weight[i]] + value[i]);
            }
        }
    }
    cout << dp[N - 1][M] << endl;
}

在上面代码的基础上,使用滚动数组,注意这里的计算要用到j-weight[i]的部分,所以要倒着算,在前面的发生变化之前,先把后面的计算了。

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int weight[3505];
int value[3505];
int dp[13005];//dp[i][j]:考虑前i种物品,容积为j时的最大价值
int main()
{
    memset(dp, 0, sizeof(dp));
    int N, M;
    cin >> N >> M;
    for (int i = 0; i < N; i++)
        cin >> weight[i] >> value[i];
    for (int i = 0; i < N; i++) {
        for (int j = M; j >= 0; j--) {
            if (j >= weight[i]) {
                dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
            }
        }
    }
    cout << dp[M] << endl;
}

 

posted @ 2021-07-09 20:32  永远是个小孩子  阅读(47)  评论(0编辑  收藏  举报