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

来源:互联网 发布:超短线战法 知乎 编辑:程序博客网 时间:2024/06/18 09:22

题目链接:

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 1010 15 105 10 53 105 10 53 5 62 7 3
 

Sample Output
511


题目意思:

有 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 0