• Proud Merchants (关于背包顺序的一个反思)


    Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerful kingdom in the world. As a result, the people in this country are still very proud even if their nation hasn’t been so wealthy any more. 
    The merchants were the most typical, each of them only sold exactly one item, the price was Pi, but they would refuse to make a trade with you if your money were less than Qi, and iSea evaluated every item a value Vi. 
    If he had M units of money, what’s the maximum value iSea could get? 
     

    Input

    There are several test cases in the input. 

    Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money. 
    Then N lines follow, each line contains three numbers Pi, Qi and Vi (1 ≤ Pi ≤ Qi ≤ 100, 1 ≤ Vi ≤ 1000), their meaning is in the description. 

    The input terminates by end of file marker. 
     

    Output

    For each test case, output one integer, indicating maximum value iSea could get. 
     

    Sample Input

    2 10
    10 15 10
    5 10 5
    3 10
    5 10 5
    3 5 6
    2 7 3

    Sample Output

    5
    11

    背包问题状态从j转移到j-a[i]时j并未真正的出现是在后面的循环中实现的

    所以背包是一个逆序的过程

    所以进行反向贪心

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<iostream>
    #include<set>
    using namespace std;
    struct node
    {
        int q;
        int p;
        int v;
    }a[1006];
    bool cmp1(node x,node y)
    {
        return x.q-x.p<y.q-y.p;
    }
    int dp[5005];
    int main()
    {
        int n,m;
        while(~scanf("%d%d",&n,&m))
        {
            memset(dp,0,sizeof(dp));
            for(int i=1;i<=n;i++)
                scanf("%d%d%d",&a[i].p,&a[i].q,&a[i].v);
            sort(a+1,a+1+n,cmp1);
            cout<<endl;
            for(int i=1;i<=n;i++) cout<<a[i].p<<" "<<a[i].q<<endl;
            cout<<endl;
            for(int i=1;i<=n;i++)
            {
                for(int j=m;j>=0;j--)
                {
                    if(j>=a[i].q) dp[j]=max(dp[j-a[i].p]+a[i].v,dp[j]);
                }
            }
            printf("%d
    ",dp[m]);
        }
        return 0;
    }
    
  • 相关阅读:
    浅谈均值、方差、标准差、协方差的概念及意义
    数据库设计的基本步骤
    VS添加lib库
    Android activity_main.xml删除边缘距离,充满屏幕
    Android 设置旋转朝向
    WebStorm注册码
    VS禁止特定警告
    VS 高亮显示不带后缀的C++头文件
    VS2010设置C++包含目录和库目录
    读取STL模型
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852325.html
Copyright © 2020-2023  润新知