大致题意:有n组数,每组数有三个数,pi,买这种物品你有的钱必须大于qi,你所能获得的价值vi。如果你想要买这种物品你所拥有的钱必须大于qi。
问你能用你所有的钱最多能获得多大价值。
解题思路:以第二组数据为例:A:5 10 5 B:3 5 6如果先买A的再买B的话需要花10块钱,但是先买B再买A的话需要13块钱。也就是花不同的钱却获得了相同的价值。所以这里排序就比较关键了!怎么排呢?还是以上面为例,先买A再买B花费p1+q2,先买B再买A花费p2+q1,p1+q2<p2+q1(为了使数据满足一定的顺序进行购买,因此我们使所有的数据都按照(q1-p1>q2-p2)这样的顺序排序,这样购买最终我们所需的钱数就是最少的,也就是拿同样多的钱,我们可以买更大价值的东西!在这里p1+q2<p2+q1与q1-p1>q2-p2等价,只不过在这里我们将描述同一个物体的变量放到不等式的一边(q1-p1>q2-p2),然后再进行排序操作比较方便罢了),如果我们都按照这样的顺序(qi-pi从大到小的顺序)进行排序,然而事实并非这样!!!请往下看(网上大神的解释......)
其实01背包的购买都是按照从后向前的顺序进行购买的,也就是说,它的每次的最后一个商品是确定购买的,然后再加上前面的除下用的最后一个的钱之后能够够购买的最大的价值与不购买这个物品进行比较,哪个大就选哪个!(在这个过程中因为是先确定后面的物品是否购买,所以我们要将差值(qi-pi)大的放到后面,差值小的放到前面,也就是前面说的按照从大到小的顺序是进行购买的顺序,而真正排序,然后按照背包执行程序的时候是按照从小到大的顺序!)
总之,就是按照差值(qi-pi)从小到大排序,然后用01背包的方法进行操作就行了!
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?
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?
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.
2 10 10 15 10 5 10 5 3 10 5 10 5 3 5 6 2 7 3
5 11
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,p[1010],q[1010],v[1010],dp[1010][5010];
struct node
{
int p,q,v;
} a[1010];
int cmp(node a,node b)
{
return (a.q-a.p)<(b.q-b.p);
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m))
{
memset(dp,0,sizeof(dp));
for(i=1; i<=n; i++)
{
scanf("%d%d%d",&a[i].p,&a[i].q,&a[i].v);
}
sort(a+1,a+n+1,cmp);//按照差价从小到大排序
for(i=1; i<=n; i++)
{
for(j=0; j<=m; j++)
{
dp[i+1][j]=dp[i][j];
if(j>=a[i].q)//只有大于去a[i].q才能购买
{
dp[i+1][j]=max(dp[i][j],dp[i][j-a[i].p]+a[i].v);
}
}
}
printf("%d\n",dp[n+1][m]);
}
return 0;
}