题面
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
参考链接
题意简述
iSea去买东西
每个物品有3个属性p,q,v
p:价格
q:买该物品时,iSea至少要拥有q元钱
v:价值
求能买到的物品的最大总价值
分析
假设有两个物体A,B;
pa,qa,va
pb,qb,vb
先买A,再买B,需要的最少钱数是pa+qb,最多是qa+qb;
先买B,再买A,需要的最少钱数是pb+qa,最多是qa+qb;
如果要先买A,则pa+qb<pb+qa
pa-qa<pb-qb
根据上述不等式,对物品的购买顺序进行排序
程序
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 505
struct Item
{
int p,q,v;
}item[maxn];
bool cmp(const Item &a,const Item &b)
{
return a.p-a.q<b.p-b.q;
}
int dp[5005];
int main()
{
int N,M;
while(scanf("%d%d",&N,&M)!=EOF)
{
memset(dp,0,sizeof(dp));
for(int i=0;i<N;i++)
scanf("%d%d%d",&item[i].p,&item[i].q,&item[i].v);
sort(item,item+N,cmp);
for(int i=0;i<N;i++)
for(int j=M;j>=item[i].p;j--)
if(M-(j-item[i].p)>=item[i].q)
dp[j]=max(dp[j],dp[j-item[i].p]+item[i].v);
int answer=0;
for(int i=0;i<=M;i++)
answer=max(answer,dp[i]);
printf("%d\n",answer);
}
return 0;
}