Proud Merchants

来源:互联网 发布:淘宝售后主管岗位职责 编辑:程序博客网 时间:2024/06/14 19:21

Proud Merchants

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 6803    Accepted Submission(s): 2840


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
 
题目大意:
手中总共有m的钱,需要在n件物品中买一定数量的物品,每件商品的价值为u,使得买到之后手中的价值w最大;
但是,每买一件商品时,手中剩下的钱必须大于v老板才同意和你交易,问能够买到的价值最大是多少?
 
解题思路;
典型的动态规划问题,但是需要注意的是,先将每件商品老板同意与你交易的最小价值v与商品的价格u的差值按从小到大的顺序排好序
这样保证了尽量多的利用空间
如果先买A后买B需要(不等于花费)u1+v2,如果先买B后买A需要v1+u2,选择两者之中较小的能保证遍历所有情况。 若先买A,则u1+v2 < v2+u1 ,即v2-u2 < v1-u1。故应先买v-u较大的 考虑0/1背包中的更新其实是逆向的,所以要把v-u从小到大排序,再做01背包。
 
 
代码如下:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct node{    int u,v,w;    int cha;} q[5050];

bool cmp(node a,node b){    return a.cha<b.cha;      //将差值按从小到大顺序排列}

int main(){    int n,m;    int dp[5050];    while(~scanf("%d%d",&n,&m))    {        memset(dp,0,sizeof(dp));        for(int i=0; i<n; i++)        {            scanf("%d%d%d",&q[i].u,&q[i].v,&q[i].w);            q[i].cha=q[i].v-q[i].u;        }        sort(q,q+n,cmp);        for(int i=0; i<n; i++)            for(int j=m; j>=q[i].v; j--) //选择手中的钱大于商家要求的最少钱            {                dp[j]=max(dp[j],dp[j-q[i].u]+q[i].w);  //计算最大能够拥有的商品价值            }        printf("%d\n",dp[m]);    }    return 0;}