Proud Merchants
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 1365 Accepted Submission(s): 562
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?
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
题目大意:骄傲商人。
在一座城市里的商人有这样一个规定,即每样物品价格为pi,但是必须当你的钱多于qi的时候你才可以去买它,而每个物品都有它对应的价值。现在你有M元大洋吗,问你最多能买多少价值的东西?
能看出来时一个01背包问题,不过很麻烦的是对于每个物品多了一个属性,qi。而qi则是阻挠我们直接dp的最大问题。想了很久,不得其所。然后开始百度,百度。。。看到了大神们的解题报告。然后要按照qi-pi进行升序排序。最后按照排好的序进行dp。
这里还要解决一个问题,就是为什么要这样排序呢?很多解释,个人认为最好理解的就是qi-pi是不用变化的范围,范围按照从小到大排,则不会出现问题。
AC代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 #include <iostream> 5 using namespace std; 6 struct Node 7 { 8 int p; 9 int q; 10 int v; 11 }node[600]; 12 int M, N; 13 bool cmp(Node a, Node b) 14 { 15 return a.q-a.p < b.q-b.p; 16 } 17 int Max(int a, int b) 18 { 19 return a > b ? a : b; 20 } 21 int main() 22 { 23 int i, j, dp[6000]; 24 while(scanf("%d%d", &N, &M) != EOF) 25 { 26 memset(dp, 0, sizeof(dp)); 27 for(i = 0; i < N; i ++) 28 { 29 scanf("%d%d%d", &node[i].p, &node[i].q, &node[i].v); 30 } 31 sort(node, node+N, cmp); 32 for(i = 0; i < N; i ++) 33 { 34 for(j = M; j>= node[i].q; j--) 35 { 36 dp[j] = Max(dp[j], dp[j-node[i].p]+node[i].v); 37 } 38 } 39 printf("%d\n", dp[M]); 40 } 41 return 0; 42 }
我们都是颜色不一样的海。
浙公网安备 33010602011771号