HDU 3466 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.

题意:01背包问题,就是用一定数量的钱可以购买到的最大的价值,但是在购买过程中会判断你拥有的钱是否小于某个值q,如果你的容量小于q,就无法购买,求可以买到的最大价值;
 
题解:
此题关键在于 发现购买商品会产生顺序的问题,

其实就是dp后效性的问题,除了i和v这2个维度还多了一个维度q,直接套用公式无法去除后效性,
先找到选择顺序的规律,去除后效性,再使用01背包;

选取的规律: 比如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从小到大排序,
因为你买第n件商品的时候,是在比较你是否要先买第n件商品。
打个比方让大家更好地理解,比如说f(3, 10),是不是max(f(2, 10-p3)+v3, f(2, 10)),
你会发现这个第一种情况f(2,10-p3)+v3中,是先买了第三件商品,也就是说排在后面的商品会先买。(重点)

还有一个要注意的:我们背包问题写的状态转移方程是从后往前选的(一维);

 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 struct GOOD{
 8     int c, q, w;
 9 }g[507];
10 
11 bool cmp(GOOD x, GOOD y){
12     return x.q-x.c<y.q-y.c;
13 }
14 
15 int main()
16 {
17     int n, V, f[5007];
18     while(cin>>n>>V)
19     {
20         memset(f, 0, sizeof(f));
21         for(int i=1; i<=n; i++)
22             cin>>g[i].c>>g[i].q>>g[i].w;
23         sort(g+1, g+n+1, cmp);
24 
25         for(int i=1; i<=n; i++)
26             for(int v=V; v>=g[i].q; v--)
27                 f[v]=max(f[v], f[v-g[i].c]+g[i].w);
28         cout<<f[V]<<endl;
29     }
30     return 0;
31 }

 

 

转载于:https://www.cnblogs.com/Yokel062/p/10702180.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值