Proud Merchants
Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerful kingdom in the world. As a result, the people in this country are still very proud even if their nation hasn’t been so wealthy any more.
The merchants were the most typical, each of them only sold exactly one item, the price was Pi, but they would refuse to make a trade with you if your money were less than Qi, and iSea evaluated every item a value Vi.
If he had M units of money, what’s the maximum value iSea could get?
Input
There are several test cases in the input.
Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money.
Then N lines follow, each line contains three numbers Pi, Qi and Vi (1 ≤ Pi ≤ Qi ≤ 100, 1 ≤ Vi ≤ 1000), their meaning is in the description.
The input terminates by end of file marker.
Output
For each test case, output one integer, indicating maximum value iSea could get.
Sample Input
2 10
10 15 10
5 10 5
3 10
5 10 5
3 5 6
2 7 3
Sample Output
5
11
题意大致是有一群商人卖东西,但是他们非常的高傲,你的钱如果少于他们规定的qi 无论你的钱够不够都不把东西卖给你,每个商人都只有一件东西(就是说只能选一样 01包) 输入的三个数是商品的价格,他规定的价格和你评测商品的价值,最终问你能买到的东西的价值最高是多少
代码我刚开始wa了几次,感觉不是01包这么简单,于是看了一下vj大佬 发现他们都加了一句排序 加上就对了233
此题中,在考虑 i 物品时,保证 j >= q[i] 才能购买,因此 j - p[i] >= q[i] - p[i],先买的物品 q[i] - p[i] 的值越大,就能用更多钱考虑买前 i - 1 件物品(贪心策略) 代码:
#include<bits/stdc++.h>
using namespace std;
int dp[10000];
struct node {
int pi;
int qi;
int vi;
}a[1050];
bool cmp(node a,node b) {
return a.qi-a.pi<b.qi-b.pi;
}
int main() {
int n,m;
while(cin>>n>>m) {
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
cin>>a[i].pi>>a[i].qi>>a[i].vi;
sort(a,a+n,cmp);
for(int i=0;i<n;i++)
for(int j=m;j>=a[i].qi;j--)
dp[j]=max(dp[j],dp[j-a[i].pi]+a[i].vi);
cout<<dp[m]<<endl;
}
}
dp用的是基本的01包的板子,注意遍历j的时候不要>=0 刚开始我觉得这样方便于是都这样写,后来发现不太行,因为可能会出现
数组负下标,这里题目明确说了q[i]>p[i]所以直接大于等于q[i]即可