某种排序下的01背包,直接01背包肯定是错的,因为题目加了一些限制,需按q-p 从小到大将物品排序,至于为什么还是不清楚

View Code
#include<iostream>
#include<algorithm>
using namespace std;
int dp[5005];
struct good
{
int p,q,v;
}g[505];
bool cmp(good a,good b)
{
return a.q-a.p<b.q-b.p;
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)==2)
{
for(int i=0;i<n;i++)
scanf("%d %d %d",&g[i].p,&g[i].q,&g[i].v);
sort(g,g+n,cmp);
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
{
for(int j=m;j>=0;j--)
{
if(j<g[i].q || j-g[i].p<0)
continue;
dp[j]=max(dp[j],dp[j-g[i].p]+g[i].v);
}
}
int ans=0;
for(int i=0;i<=m;i++)
if(dp[i]>ans)
ans=dp[i];
printf("%d\n",ans);
}
return 0;
}

 

相关文章:

  • 2022-12-23
  • 2021-06-10
  • 2021-05-29
  • 2021-06-10
  • 2021-07-20
  • 2021-08-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2021-09-18
  • 2021-11-20
  • 2022-12-23
相关资源
相似解决方案