动态规划的过程中,较差的状态会被更优的状态覆盖。
最大的价值,需要建立在最优的状态上,几个较优的物品组合在一起,才能出最优解,所以把优劣分开。
先根据每个物品的代价排序(本题的代价为q-w),最差的物品,最先使用,便能被后面的物品覆盖状态,才能得到最优解。
#include<bits/stdc++.h>
using namespace std;
#define MAXN 5005
#define ll long long
struct node{
int w,q,v;
}p[MAXN];
int dp[MAXN];
bool cmp(node a,node b){
if(a.q-a.w>b.q-b.w)return true;
return false;
}
int main(){
int n,m;
while(cin>>n>>m){
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
scanf("%d%d%d",&p[i].w,&p[i].q,&p[i].v);
}
sort(p+1,p+1+n,cmp);
int ans=0;
for(int i=1;i<=n;i++){
for(int j=p[i].w;j<=m;j++){
if(j>=p[i].q){
//dp[j]表示当前还有j元的最大价值
dp[j-p[i].w]=max(dp[j-p[i].w],dp[j]+p[i].v);
ans=max(ans,dp[j-p[i].w]);
}
}
for(int j=1;j<=m;j++){
cout<<dp[j]<<" ";
}
cout<<endl;
}
cout<<ans<<endl;
}
return 0;
}