• 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;
    }
  • 相关阅读:
    tomcat部署https
    Java程序内存的简单分析
    接口设计原则
    英语常用口语
    洛谷 P3956 棋盘
    洛谷 P1101 单词方阵
    二分查找模板(准确找定值)
    洛谷 P1892 [BOI2003]团伙
    浅谈二分的边界问题
    deque简单解析
  • 原文地址:https://www.cnblogs.com/LuRenJiang/p/7399344.html
Copyright © 2020-2023  润新知