1. #include <iostream>
    2. #include <functional>
    3. #include <numeric>
    4. #include <algorithm>
    5. using namespace std;
    6. class Solver1 {
    7. /*
    8. f[i][j] 表示 只看前 i 个物品,背包大小为 j 时的最大价值
    9. result = max(f[n][0-v])
    10. f[i][j]:
    11. 1. 不选 i ,f[i][j] = f[i - 1][j]
    12. 2. 选 i ,f[i][j] = f[i - 1][j - w[i]] + v[i]
    13. f[0][0] = 0
    14. */
    15. const static int MAXN = 1000 + 5;
    16. int dp[MAXN][MAXN];
    17. int w[MAXN], v[MAXN];
    18. public:
    19. void f() {
    20. int N, V;
    21. cin >> N >> V;
    22. for (int i = 1; i <= N; i++)
    23. cin >> v[i] >> w[i];
    24. for (int i = 1; i <= N; i++)
    25. for (int j = 0; j <= V; j++) {
    26. dp[i][j] = dp[i - 1][j];
    27. if (j >= v[i])
    28. dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - v[i]] + w[i]);
    29. }
    30. cout << dp[N][V] << endl;
    31. }
    32. };
    33. class Solver2 {
    34. /*
    35. 一维优化
    36. */
    37. static const int MAXN = 1000 + 5;
    38. int v[MAXN], w[MAXN];
    39. int dp[MAXN] = {};
    40. public:
    41. void f() {
    42. int N, V;
    43. cin >> N >> V;
    44. for (int i = 1; i <= N; i++)
    45. cin >> v[i] >> w[i];
    46. for (int i = 1; i <= N; i++)
    47. for (int j = V; j >= v[i]; j--)
    48. dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
    49. cout << dp[V] << endl;
    50. }
    51. };
    52. class Solver3 {
    53. static const int MAXN = 1000 + 5;
    54. static const int INF = 0x3f3f3f3f;
    55. int v[MAXN], w[MAXN];
    56. int dp[MAXN];
    57. public:
    58. void f() {
    59. int N, V;
    60. cin >> N >> V;
    61. for (int i = 1; i <= N; i++)
    62. cin >> v[i] >> w[i];
    63. dp[0] = 0;
    64. for (int i = 1; i <= V; i++) dp[i] = -INF;
    65. for (int i = 1; i <= N; i++)
    66. for (int j = V; j >= v[i]; j--)
    67. dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
    68. cout << *max_element(dp, dp + V + 1) << endl;
    69. }
    70. };
    71. int main() {
    72. Solver1 s1;
    73. Solver2 s2;
    74. Solver3 s3;
    75. srand(time(NULL));
    76. int tmp = rand() % 3;
    77. if (tmp == 0) s1.f();
    78. else if (tmp == 1) s2.f();
    79. else s3.f();
    80. }