hdu Proud Merchants

Proud Merchants

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 84 Accepted Submission(s): 46
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
这一题是一个背包问题。比较关键的是:为了尽可能的使取得最大Vi时背包装得较满,
我们要对“Qi与Pi的差”从大到小排序。比如下面这个实例:
4 20
5 15 20
8 12 19
2 16 21
9 11 13
如果不排序,直接进行动态规划的话
2 16 21这个物品相当于没有放入背包,因为假如你先选择前两种物品的话,
2 16 21就会因为16这个条件不能与前两种物品同时放入背包,但是如果提前排好序就不一样了。
这一点处理好,这一题基本就没问题了。
 1 #include <iostream>
2 #include <stdio.h>
3 #include <algorithm>
4 #include <string.h>
5 using namespace std;
6 int f[5001];
7 typedef struct
8 {
9 int p,q,v;
10 }item;
11 bool cmp(item a,item b)
12 {
13 return a.q-a.p<b.q-b.p;
14 }
15 int main()
16 {
17 int n,m;
18 item it[501];
19 while(scanf("%d%d",&n,&m)!=EOF)
20 {
21 for(int i = 0; i < n; i++)
22 {
23 scanf("%d%d%d",&it[i].p,&it[i].q,&it[i].v);
24 }
25 sort(it,it+n,cmp);
26 memset(f,0,sizeof(f));
27 for(int i = 0; i < n; i++)
28 for(int j = m; j>=it[i].q;j--)
29 {
30 if(f[j-it[i].p]+it[i].v>f[j])
31 f[j] = f[j-it[i].p]+it[i].v;
32 }
33 printf("%d\n",f[m]);
34 }
35 return 0;
36 }

你可能感兴趣的:(ant)