Charm Bracelet

Posted 路人姜。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
来源
USACO 2007 December Silver
OJ:openjudge
参考代码
///01背包问题
#include <iostream>

using namespace std;
int d[3403];//‘desirability‘
int w[3403];//重量
int dp[3403][12881];//dp[i][j],i表示拿前i件,j表示总重不能超过j
int main()
{
    int n,m;//n:项链件数,m:不能超过的重量
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>w[i]>>d[i];
    }
    //为边界赋值,拿前1件的情况
    if(w[1]<m){
        dp[1][m]=w[1];
    }
    else{
        dp[1][m]=0;
    }

    int i,j;
    for(i=1;i<=n;i++){
        for(j=0;j<=m;j++){
            if(j<w[i]){
                dp[i][j]=dp[i-1][j];
            }
            else{
                dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+d[i]);
            }
        }
    }
    cout<<dp[n][m]<<endl;
    return 0;
}

我还写了个,滚动数组的写法,可是在一个大数的测试WA了/(ㄒoㄒ)/~~,各位给看看哪里错了,或者贴个滚动数组的写法,欢迎交流,感激不尽。

///01背包问题,滚动数组
#include <iostream>
using namespace std;
int d[3403];//‘desirability‘
int w[3403];//重量
int dp[1288071];//dp[i][j],i表示拿前i件,j表示总重不能超过j
int main()
{
    int n,m;//n:项链件数,m:不能超过的重量
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>w[i]>>d[i];
    }
    //为边界赋值,拿前1件的情况
    if(w[1]<m){
        dp[1]=w[1];
    }
    else{
        dp[1]=0;
    }
    for(int i=0;i<=n;i++){
        for(int j=m;j>=w[i];j--){
                dp[j]=max(dp[j],dp[j-w[i]]+d[i]);
        }
    }
    cout<<dp[m]<<endl;
    return 0;
}

 

以上是关于Charm Bracelet的主要内容,如果未能解决你的问题,请参考以下文章

Charm Bracelet

Charm Bracelet

poj 3624 Charm Bracelet

POJ-3624-Charm Bracelet

Charm Bracelet(01背包问题)

dp--01背包--Charm Bracelet