題意
給定n個物品和錢數m,每個物品的價格p,限制錢數q,價值v,限制q的意思是你手頭的錢必須大於等於q才能購買這個物品,問最後獲得的最大價值。
思路
假設兩個物品a,b,我們都要買下來,需要的錢至少是pa+pb+max(qa-pa,qb-pb),也就是先買差值最大的,留下來的錢可以滿足差值小的的限制價格;
由於動態規劃先更新的是子狀態,所以要先更新差值小的,也就是qa-pa<qb-pb`在這裏插入代碼片`;
代碼
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=505,M=5005;
struct node
{
int p,q,v;
bool operator < (const node t)
{
return q-p<t.q-t.p;
}
} a[N];
int dp[M];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
memset(dp,0,sizeof dp);
for(int i=0; i<n; i++)
scanf("%d%d%d",&a[i].p,&a[i].q,&a[i].v);
sort(a,a+n);
for(int i=0; i<n; i++)
for(int j=m; j>=a[i].q; j--)
dp[j]=max(dp[j],dp[j-a[i].p]+a[i].v);
printf("%d\n",dp[m]);
}
return 0;
}