题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=3466
这是一道01背包的变形题,题目增加了一个限制条件,即当你所拥有的钱数大于某个限定值时才可以购买该物品。
按照q - p以由大到小的顺序排序,然后进行01背包的DP即可。
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1
#include
<
iostream
>
2 #include < algorithm >
3 using namespace std;
4
5 const int M = 5005 ;
6 struct Goods
7 {
8 int p, q, v;
9 }merchants[M];
10
11
12 int cmp(Goods a, Goods b)
13 {
14 return (a.q - a.p) < (b.q - b.p);
15 }
16
17 int main()
18 {
19 int n, m;
20 while (scanf( " %d%d " , & n, & m) != EOF)
21 {
22 int dp[M] = { 0 };
23 for ( int i = 0 ; i < n; i ++ )
24 scanf( " %d%d%d " , & merchants[i].p, & merchants[i].q, & merchants[i].v);
25
26 sort(merchants, merchants + n, cmp);
27 int res = m;
28 for ( int i = 0 ; i < n; i ++ )
29 {
30 for ( int j = m; j >= max(merchants[i].p,merchants[i].q); j -- )
31 {
32
33 if (dp[j] < (dp[j - merchants[i].p] + merchants[i].v))
34 {
35 dp[j] = dp[j - merchants[i].p] + merchants[i].v;
36 }
37
38 }
39 }
40 int ans = - 1 ;
41 for ( int i = 0 ; i <= m; i ++ )
42 if (ans < dp[i]) ans = dp[i];
43 printf( " %d\n " ,dp[m]);
44 }
45 return 0 ;
46 }
47
2 #include < algorithm >
3 using namespace std;
4
5 const int M = 5005 ;
6 struct Goods
7 {
8 int p, q, v;
9 }merchants[M];
10
11
12 int cmp(Goods a, Goods b)
13 {
14 return (a.q - a.p) < (b.q - b.p);
15 }
16
17 int main()
18 {
19 int n, m;
20 while (scanf( " %d%d " , & n, & m) != EOF)
21 {
22 int dp[M] = { 0 };
23 for ( int i = 0 ; i < n; i ++ )
24 scanf( " %d%d%d " , & merchants[i].p, & merchants[i].q, & merchants[i].v);
25
26 sort(merchants, merchants + n, cmp);
27 int res = m;
28 for ( int i = 0 ; i < n; i ++ )
29 {
30 for ( int j = m; j >= max(merchants[i].p,merchants[i].q); j -- )
31 {
32
33 if (dp[j] < (dp[j - merchants[i].p] + merchants[i].v))
34 {
35 dp[j] = dp[j - merchants[i].p] + merchants[i].v;
36 }
37
38 }
39 }
40 int ans = - 1 ;
41 for ( int i = 0 ; i <= m; i ++ )
42 if (ans < dp[i]) ans = dp[i];
43 printf( " %d\n " ,dp[m]);
44 }
45 return 0 ;
46 }
47