hdu 3466 Proud Merchants(贪心+DP)

Proud 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件商品,每件商品的价格是pi,每件商品只有在你的钱大于等于qi时才可以买入,每件商品都有一个价值vi。现在你有m元钱,如何实现使买到的商品价值最大

思路:很明显是一个01背包,但是你会发现单纯的01背包并不适用。要使买到的商品价值最大,肯定跟购买的顺序有关,所以这要用到贪心的思想,关键就是该怎样贪心

比如说这组样例:
3 10
5 5 5 —-A商品
3 3 6 —-B商品
2 3 3 —-C商品

你会发现如果要买C商品的话,肯定得先买C商品,因为买C商品的代价最大,所以我们可以按照qi-pi的顺序来确定购买顺序

可以来证明一下,比如
A:p1 q1 , B:p2 q2
然后,单独买A或者买B的话都可以买到。这时,如果先买A,那至少需要花费p1+q2的钱;如果先买B,至少需要花费p2+q1的钱。假如先买A再买B的花费更小,那么则有p1+q2<p2+q1,转换一下,就是q1-p1>q2-p2,也就是说让qi-pi大的先买。
因此我们需要按照qi-pi的值从小到大排序。这里需要注意一下,为什么是按照从小到大排序呢?
想一下,01背包是for(j=m;j>pi;j–),也就是说排在后面的物品会先买,所以就是从小到大排序了

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) (a>b?a:b)
#define maxn 500+10
#define N 5000+10

struct node
{
    int pi,qi,vi,cost;
    friend bool operator < (node a,node b)
    {
        return a.cost<b.cost;
    }
} q[maxn];
int dp[N];

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        mem(dp,0);
        for(int i=0; i<n; i++)
        {
            scanf("%d%d%d",&q[i].pi,&q[i].qi,&q[i].vi);
            q[i].cost=q[i].qi-q[i].pi;
        }
        sort(q,q+n);
        for(int i=0; i<n; i++)
            for(int j=m; j>=q[i].qi; j--)
                dp[j]=max(dp[j],dp[j-q[i].pi]+q[i].vi);
        printf("%d\n",dp[m]);
    }
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值