Source: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 3466
This is a backpack deformation question. A restriction is added to the question, that is, you can purchase this item only when the amount of money you have exceeds a certain limit.
Sort Q-P in ascending order, and then perform the dp of the 01 backpack.
Code
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 " , & N, & M) ! = EOF)
21 {
22 Int DP [m] = { 0 };
23 For ( Int I = 0 ; I < N; I ++ )
24 Scanf ( " % 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