01背包简单处理
原文:
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?
输入:
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.
输出:
For each test case, output one integer, indicating maximum value iSea could get.
#include<string>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
const int N = 1010;
typedef long long LL ;
//如果去掉q的约束,其实就是一道简单的01背包,因此就是如何处理p的约束
//在这里,可以知道01背包就是用到了上一个物品的体积进行后续的操作
//因此上面物品体积一定要小于我们现在计算的物品
//如果我们现在计算的物品体积小于之前的某一个物品体积
//就一定会发生我们所计算的f[i]=0,比如说我们之前是5 9 3 而现在是5 5 3
//之前我们计算出了f[9]但是对于f[8],f[7]我们是初值0 因此我们需要置换顺序
struct node
{
int v,q,w;
} a[5010];
LL f[5010];
bool cmp(struct node a,struct node b)
{
return a.q-a.v<b.q-b.v;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(f,0,sizeof f);
for(int i=1;i<=n;i++) cin>>a[i].v>>a[i].q>>a[i].w;
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
for(int j=m;j>=max(a[i].v,a[i].q);j--)
f[j]=max(f[j],f[j-a[i].v]+a[i].w);
cout<<f[m]<<endl;
}
}
·