zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    memcached 高级机制(一)
    memcached 简介
    Hibernate
    Linux中的搜索命令
    Linux的常用命令
    Git清除用户名和密码
    关于Git的简单使用
    文件的上传与下载(2)
    关于文件的上传和后台接收
    验证码的制作
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852325.html
Copyright © 2011-2022 走看看