Description
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?
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.
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,每个物品有价格p,限制钱数q,价值v,限制q的意思是你手头的钱必须大于等于q才能购买这个物品,问最后获得的最大价值。
它与01背包的差别就在于他有限制,如果p==q的话就是普通的背包了,所以我们要想办法去处理限制,得到最优解!
大神们写的是用p,q的差值去从小到大排序,就是限制最小价值最大的先买,争取牺牲最小!
我的理解
第一:题中第二组数据,如果先算第一个,那么当次只有10可以进行状态转移,装第二个物品的时候6,7,8,9,10进行转移,第二个物品转移就不可以借用第一个物品的状态,但是如果第二个物品先转移,第一个再转移,第一次就是6,7,8,9,10可以状态转移,装第二个的时候就可以借用第一个的转移状态。
第二:限制又小价格又贵的先选,也就是q-p小的先选。为什么这样呢?A:p1,q1 B: p2,q2,先选A,则至少需要p1+q2的容量,而先选B则至少需要p2+q1,如果p1+q2>p2+q1,那么要选两个的话的就要先选A再选B,公式可换成q1-p1 < q2-p2,就按这样的方法排序最后的顺序就是最优的顺序。
该题要确保p-q小的先被”挑选“,差值越小使用它的价值越大(做出的牺牲越小).
#include <iostream>
#include <cstdio>
#include <algorithm>
#include<string.h>
using namespace std;
struct item
{
int p;
int q;
int v;
bool operator < (const item b)const//重载运算符,在这的功能就是排序
{
return q-p<b.q-b.p;//按照差值从小到大排
}
} tm[520];
int n , m;
int dp[5200];
int main()
{
while( scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,0,sizeof(dp));
for(int i =1; i<=n; i++)
scanf("%d%d%d",&tm[i].p,&tm[i].q,&tm[i].v);
sort(tm+1,tm+n+1);
for(int i=1; i<=n; i++)
for(int c = m; c>=tm[i].q; c--)
dp[c]=max(dp[c],dp[c-tm[i].p]+tm[i].v);//选出最优解
//其实这里先买的是5,10这组数据,而dp的是买了这个以后买不买别的,不买就是dp[c],如果还买就把买过可以得到的价值加上去
cout << dp[m]<<endl;
}
return 0;
}