HDU3466Proud Merchants——01背包问题模板套用

Problem 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?

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

这里涉及到了,为什么要把商品进行q-p的差值从小到大的排序的问题。
因为这个题目和我们以往做到的01背包问题有所不同,我们平时所做的01背包问题都是不管其顺序关系的,只要背包够了,我们就可以带走它,但是本题的我们很容易发现,购买的顺序会影响到我们最后的结果。所以我们该如何确定一个正确的购买顺序呢?我们思考一下,如果叫你判断买不买,实现价值的最大化,你会如何选择,很显然,你会选择,q大,p小的,看看它能不能买。那么,我们就可以对这些数据通过q-p进行排序了,但是为什么是从小到大排序呢?因为,01背包的过程j=m;j - -,后取得的数在前面判断,这样才能让我们的数据更新不被影响。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct Goods
{
	int p,q,v; //1≤pi≤qi≤100,1≤vi≤1000
};
Goods goods[550];
int f[5050];
int max(int x,int y)
{return x>y?x:y;}
bool cmp(Goods x,Goods y)
{
	return x.q-x.p<y.q-y.p;
}
int main()
{           //价格是pi,钱少于qi拒绝交易,评估价值为vi。
	int n,m;//项目数和初试金额 1≤n≤500,1≤m≤5000
	int i,j,k;
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		memset(f,0,sizeof(f));
		for(i=0;i<n;i++)
			scanf("%d %d %d",&goods[i].p,&goods[i].q,&goods[i].v);
		sort(goods,goods+n,cmp);
		for(i=0;i<n;i++)
			for(j=m;j>=goods[i].q;j--)
				f[j]=max(f[j],f[j-goods[i].p]+goods[i].v);
		printf("%d\n",f[m]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37230495/article/details/88318145