HDU 3466 Proud Merchants

Proud Merchants
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 8292 Accepted Submission(s): 3481

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

题目链接

题意:

给定$n$件物品,第$i$件物品价格为$p_i$,且至少需要有$q_i$元才能买,价值为$v_i$。求当有$m$元时能获得的最大价值。

Solution:

乍一看就是个普通的01背包,实际上并不是。因为至少需要有$q_i$元才能买某一件物品,所以购买的先后顺序具有后效性。
显然,当$p_{1} + q_{2} \leq k < p_{2} + q_{1}$时,先买1号物品还能再买2号物品,但先买2号物品就不能再买1号物品了,即满足$q_{1} - p_{1} > q_{2} - p_{2}$时,应先买1号再买2号。
然而我们应按照$q_i - p_i$从小到大排序,引用网上看到的:

通俗的说:这个dp过程正好是逆向的dp[c-p[i]]是dp[c]的最优子结构。所以在DP的时候我们应该按照M的值从小到大排序。

排序后直接套01背包即可。

Code:

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
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"

int id[505];
int p[505], q[505], v[505];
int dp[5005];

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

int n, m;
while (cin >> n >> m) {
for (int i = 1; i <= n; i++) {
cin >> p[i] >> q[i] >> v[i], id[i] = i;
}
sort(id + 1, id + 1 + n, [&](const int& a, const int& b) {
return q[a] - p[a] < q[b] - p[b];
});
memset(dp, 0, sizeof dp);
for (int k = 1; k <= n; k++) {
int i = id[k], edge = max(p[i], q[i]);
for (int j = m; j >= edge; j--) {
dp[j] = max(dp[j], dp[j - p[i]] + v[i]);
}
}
cout << dp[m] << endl;
}
}