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?
InputThere 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.
OutputFor 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
拿题思想:这也是一个关于买东西的问题,你有总钱数吗,买一些东西,那些东西有价格,也有对自己的价值,且加了一个属性,那就得满足一些条件;所以可以把这个问题看成01背包的问题,m即为背包的容量。
最终解题步骤:
1)首先用一个结构体来储存这个物品的价格p,属性q,价值v;
2)对这些物品进行排序,以价格低到高开始排,当价格相同时,就按属性低的排,那么我们就按照q-p从小到大开始排;
3)利用背包dp的状态转移方程解决问题;
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int dp[5005];
struct wp
{
int p,q,v;
}s[5005];
int cmp(wp a,wp b)
{
return a.q-a.p<b.q-b.p;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
cin>>s[i].p>>s[i].q>>s[i].v;
sort(s+1,s+1+n,cmp);
for(int i=1;i<=n;i++)
for(int j=m;j>=s[i].q;j--)
dp[j]=max(dp[j],dp[j-s[i].p]+s[i].v);
cout<<dp[m]<<endl;
}
return 0;
}