您的位置:首页 > 其它

HDU Problem w-dp

2018-04-01 23:41 113 查看
[align=left]Problem Description[/align]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.<br>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.<br>If he had M units of money, what’s the maximum value iSea could get?<br><br> 
[align=left]Input[/align]There are several test cases in the input.<br><br>Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money.<br>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.<br><br>The input terminates by end of file marker.<br><br> 
[align=left]Output[/align]For each test case, output one integer, indicating maximum value iSea could get.<br><br> 
[align=left]Sample Input[/align]
2 1010 15 105 10 53 105 10 53 5 62 7 3
 
[align=left]Sample Output[/align]
511

题意:买东西,每个东西有三个特征值,p代表价格,q代表你手中钱必须不低于q才能买这个物品,v代表得到的价值。
思路:
这题因为涉及到q,所以不能直接就01背包了。因为如果一个物品是5 9,一个物品是5 6,对第一个进行背包的时候只有dp[9],dp[10],…,dp[m],再对第二个进行背包的时候,如果是普通的,应该会借用前面的dp[8],dp[7]之类的,但是现在这些值都是0,所以会导致结果出错。

所以按照q-p的差从小到达排序,先判断差小的,防止出错;
code:#include<bits/stdc++.h>//万能头文件
using namespace std;
struct bag
{
int p;//价格
int q;//比较
int v;//价值
}s[505];
int dp[5005];
bool cmp(bag a,bag b)//按q-p排序,保证差额最小为最优
{
return a.q-a.p<b.q-b.p;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;++i)
cin>>s[i].p>>s[i].q>>s[i].v;
sort(s+1,s+n+1,cmp);//排序
for(int i=1;i<=n;++i)
{
for(int j=m;j>=s[i].q;--j)//剩余的钱数必须>s[i].q
dp[j]=max(dp[j],dp[j-s[i].p]+s[i].v);
}
cout<<dp[m]<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: