Title Description
Solution: sequencing + 0-1 knapsack problem
First explain how to deal with the lowest transaction price The problem:
Example. 1
. 3 10
. 5 10. 5 (Commodity A)
. 3. 5. 6 (Commodity B)
2. 7. 3
If we buy merchandise to buy A B goods, the total value is 11; if the first buy goods B, then the next time will not be able to buy top grade of A, the description lowest trading prices mainly reflected on the issue of the purchase order.
Suppose product A, B, the corresponding figures were with If the first to buy A buy B, then at least need Money; if you at least need to turn Money. Let us assume that at this time of the purchase order first and then A B so spend the least money, then there is inequality , which is So it says large commodity should give priority to buy, so we follow value of a commodity prior to ordering.
Then we think about a problem: large goods to buy, then it should be sorted according to values from small to large, from large to small or do? 0-1 knapsack problem is the reverse enumeration, when it should be sorted in ascending order, thus ensuring large commodity to purchase
Finally, loop inside, we should to , because it not only meets the minimum trading price also meet plenty of money to buy items
#include <iostream>
#include <algorithm>
using namespace std;
struct commodity{
int p, q, v;
};
bool cmp(commodity a, commodity b)
{
return a.q-a.p<b.q-b.p;
}
int main()
{
int n, m;
while(~scanf("%d%d", &n, &m))
{
commodity com[505] = {0};
int dp[5005] = {0};
for(int i=1;i<=n;i++)
scanf("%d%d%d", &com[i].p, &com[i].q, &com[i].v);
sort(com, com+n, cmp);
for(int i=1;i<=n;i++)
for(int j=m;j>=com[i].q;j--)
dp[j] = max(dp[j], dp[j-com[i].p]+com[i].v);
printf("%d\n", dp[m]);
}
return 0;
}