/* * 背包 DP:考虑前 i 个物品的最大价值,在仅有 t 容量的情况下。 * 建议两个维度调换一下,方便乒乓/滚动。 */ #include using namespace std; struct Item { int weight, value; }; constexpr int MAX_N = 105, MAX_CAPACITY = 1005; int capacity, n; Item items[MAX_N]; int dp[MAX_CAPACITY][MAX_N]; void solve_dp() { for (int i = 0; i <= capacity; i++) { dp[i][0] = 0; } for (int i = 0; i <= n; i++) { dp[0][i] = 0; } for (int stop_item = 1; stop_item <= n; stop_item++) { for (int w = 1; w <= capacity; w++) { dp[w][stop_item] = dp[w][stop_item - 1]; if (w >= items[stop_item - 1].weight) { // 负数 dp[w][stop_item] = max(dp[w][stop_item], dp[w - items[stop_item - 1].weight][stop_item - 1] + items[stop_item - 1].value); } } } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> capacity >> n; for (int i = 0; i < n; i++) { cin >> items[i].weight >> items[i].value; } solve_dp(); cout << dp[capacity][n] << endl; return 0; }