Problem
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
题解
题目大意就是给出N个物品和M个单位的钱,第 i i i件物品价格为 P i P_i Pi,价值为 V i V_i Vi,只有你手中的钱大于等于 Q i Q_i Qi才能购买第 i i i件物品。求能买到的物品的价值的最大值为多少。多组数据。
很明显使用01背包。但是要做一些预处理。各个物品按 ( Q i − P i ) (Q_i-P_i) (Qi−Pi)从大到小排序,再做01背包。
为什么呢?假设需要购买物品 i i i和物品 j j j,如果先买 i i i再买 j j j,则至少需要 max ( Q j + P i , Q i ) \max(Q_j+P_i,Q_i) max(Qj+Pi,Qi)元,先买 j j j再买 i i i,则至少需要 max ( Q i + P j , Q j ) \max(Q_i+P_j,Q_j) max(Qi+Pj,Qj)元。同样买两种物品,最初的金额要求一定要最小才能最优。比较 max ( Q j + P i , Q i ) \max(Q_j+P_i,Q_i) max(Qj+Pi,Qi)和 max ( Q i + P j , Q j ) \max(Q_i+P_j,Q_j) max(Qi+Pj,Qj)。因为 Q i Q_i Qi和 Q j Q_j Qj在另一方中也出现过,所以可以省略,不影响大小的判断。所以我们只需要比较 Q j + P i Q_j+P_i Qj+Pi和 Q i + P j Q_i+P_j Qi+Pj。移项后就是 Q j − P j Q_j-P_j Qj−Pj和 Q i − P i Q_i-P_i Qi−Pi,也就是上面的式子。如果 Q i − P i > Q j − P j Q_i-P_i>Q_j-P_j Qi−Pi>Qj−Pj,则先选 i i i后选 j j j更优。所以我们要先选 Q i − P i Q_i-P_i Qi−Pi大的物品。
code
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int n,m,ans,f[5005];
struct node{
int p,q,k;
}v[505];
bool cmp(node ax,node bx){
return ax.q-ax.p>bx.q-bx.p;
}
int max(int a,int b){
return a>b?a:b;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=1;i<=n;i++){
scanf("%d%d%d",&v[i].p,&v[i].q,&v[i].k);
}
sort(v+1,v+n+1,cmp);
for(int i=0;i<m;i++) f[i]=-2147483647;
f[m]=0;
for(int i=1;i<=n;i++){
for(int j=v[i].q-v[i].p;j<=m-v[i].p;j++){
f[j]=max(f[j],f[j+v[i].p]+v[i].k);
}
}
ans=0;
for(int i=0;i<=m;i++){
ans=max(ans,f[i]);
}
printf("%d\n",ans);
}
return 0;
}