【01背包】HDU3466Proud Merchants【判断顺序】

题目链接:

Problem Description
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


题目意思:

有 n 个物品,每个物品都有一定的价值v和花费p,而且买的时候自己的钱不能低于那个物品的指标q,问最后可以买到的物品的最大价值是多少。

代码:

#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
    int p,q,v;
}stu[550];
bool cmp(node a,node b)
{
    return (a.q-a.p)<(b.q-b.p);     //  按差值由小到大排序;
    /*
        因为这个题目增加了购买的前提条件,和不同的01背包有点不同;
        哪里不同呢?不同的地方在于普通的01背包,购买顺序不影响其结果;
        但是在这里,我们可以很明白的看出来,购买顺序是会影响我们的最后结果的。
        所以我们应该确定一个正确的购买顺序;然后我们就可以想想,如果叫你判断买不买,
        实现价值最大化,你会以怎样的顺序先后判断;
        很显然,你会先判断q大,p小的物品买不买,对吧,因为在你价值最大,你应该尽可能的判断q大,p小的物品;
        明白这点,这个题目基本上就解决了;
        我们可以对数据进行排序,直接就以p,q的差值排序就可以了;
        但是这里我们需要注意的是,要以差值由小到大排序,而不是由大到小,
        想想dp的过程,j=m,j--;后取得数在前面判断,这样才能让我们的数据更新不被影响;
    */
}
int n,m;
int ZeroOnePack()
{
    int f[5050]={0};
    for(int i=0;i<n;i++)
        for(int j=m;j>=stu[i].q;j--)            //  已知q>p;
            f[j]=max(f[j],f[j-stu[i].p]+stu[i].v);
    return f[m];
}
int main()
{
    while(cin>>n>>m){
        for(int i=0;i<n;i++)cin>>stu[i].p>>stu[i].q>>stu[i].v;
        sort(stu,stu+n,cmp);
        cout<<ZeroOnePack()<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值