HDU Proud Merchants 最优解+背包

来源:互联网 发布:淘宝店铺被违规警告 编辑:程序博客网 时间:2024/06/06 09:08

Proud Merchants

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 5   Accepted Submission(s) : 2

Font: Times New Roman | Verdana | Georgia

Font Size:  

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件商品求最大价值,非常容易想到背包,但是比较特别一点的是每件商品的属性除了Pi价格,Vi价值之外,还有一个Qi起步价,也就是说如果你的钱不到Qi,那么你是没有权利买这件商品的(太傲娇了),那么我们可以这么想,假设有两件商品

A(Pa,Qa,Va),B(Pb,Qb,Vb),我们应该如何抉择到底先买哪件呢?如果我们两件都想买,那么,如果先买A,再买B,我们至少需要Pa+Qb这么多钱,如果先买B,再买A,那么至少需要Pb+Qa这么多钱,作为一名正常人,当然选择钱最少的情况,

我们不妨令Pa+Qb<Pb+Qa,移项之后就是Qa-Pa>Qb-Pb,也就是说,如果要先买A,那么A的Q-P必须要大,这就给我们提供了一个解题思路,先按照Q-P从大到小排序,然后再用01背包,但是还有一个问题,就是在背包计算的过程中,这个dp过程 正好是逆向的  ,也就是说,在考虑第n件商品的时候,我们实际上把第n件商品放在第一位优先考虑,只有第n件商品确定了,前面的商品才能确定。 所以 在DP 的时候我们应该按照 M的值从小到大排序。也就是说我们应该按照 Q-P 的值 从小到 大排序在 DP 了。


#include<iostream>#include<algorithm>using namespace std;struct Good{int P;int Q;int V;};int max(int a,int b){return a>b?a:b;}bool cmp(const Good &a,const Good &b){return (a.Q-a.P)<(b.Q-b.P);}int main(){int N,M,i,j;while(cin>>N>>M){Good *goods=new Good[N+1];int *F=new int[M+1];goods[0].P=goods[0].Q=goods[0].V=0;for(i=0;i<=M;i++)F[i]=0;for(i=1;i<=N;i++){cin>>goods[i].P>>goods[i].Q>>goods[i].V;}sort(goods,goods+N+1,cmp);for(i=0;i<=N;i++){for(j=M;j>=goods[i].P;j--){if(j>=goods[i].Q)F[j]=max(F[j],F[j-goods[i].P]+goods[i].V);}}cout<<F[M]<<endl;}return 0;}










0 0
原创粉丝点击