HDOJ-3466 Proud Merchants【01背包】

题目链接HDU-3466

题目描述

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

思路

感觉是贪心+DP? 因为01背包的状态转移是根据前i-1件物品的选择来确定第i种状态,所以对于我们这道题而言我们得先更新出那些p与q差值较小的状态,然后在确定那些p与q差值较大的状态;如果先更新差值较大的状态的话,可能会遗漏一部分
状态,使得答案不正确; 所以我们先排序,然后进行01背包,就可以做到不重不漏;

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;

#define long long long
#define MAX_N 100010
#define INF 0x3f3f3f3f

int dp[MAX_N];

struct Node{
int p, q, v;
}S[5050];

bool cmp(Node a, Node b)
{
return a.p - a.q > b.p - b.q;
}

int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);

int n, T;
while(cin >> n >> T)
{
for(int i = 1; i <= n; i++)
{
cin >> S[i].p >> S[i].q >> S[i].v;
}
sort(S+1, S+1+n, cmp);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++)
{
for(int j = T; j >= S[i].q; j--)
{
dp[j] = max(dp[j], dp[j - S[i].p] + S[i].v);
}
}
cout << dp[T] << endl;
}

return 0;
}
-------------本文结束,感谢您的阅读!-------------