针对单个物品好理解贪心策略,两个物品相对比的思路不易理解。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 550;
int n, m;
struct Node
{
int p, q, v;
}goods[maxn];
int dp[5050];
bool cmp(Node a, Node b)
{
return a.q - a.p < b.q - b.p; //理解重点
}
int main()
{
while(scanf("%d%d", &n, &m) == 2)
{
int a, b, c;
for(int i = 1; i <= n; i++)
{
cin >> a >> b >> c;
goods[i].p = a;
goods[i].q = b;
goods[i].v = c;
}
sort(goods + 1, goods + n + 1, cmp);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++)
{
for(int j = m; j >= goods[i].q; j--)
{
dp[j] = max(dp[j], dp[j - goods[i].p] + goods[i].v);
}
}
cout << dp[m] << endl;
}
return 0;
}