$$\color{red}{算法}\color{blue}{基础课}\color{purple}{笔记and题解}\color{green}{汇总}$$
这道题直接上优化吧……(懒得写没优化的了)
和 01 背包差不多
01 背包的代码是这样的:
#include <bits/stdc++.h>
using namespace std;
int c[1010], w[1010], dp[1010], n, m;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1;i <= n; i++) scanf("%d%d", &c[i], &w[i]);
for (int i = 1;i <= n; i++)
for (int j = m; j >= c[i]; j--)
dp[j] = max(dp[j], dp[j - c[i]] + w[i]);
printf ("%d\n", dp[m]);
return 0;
}
改了个循环,从逆序改成正序,就意味着每一个物品可以选择多次:
#include <bits/stdc++.h>
using namespace std;
int c[1010], w[1010], dp[1010], n, m;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1;i <= n; i++) scanf("%d%d", &c[i], &w[i]);
for (int i = 1;i <= n; i++)
for (int j = c[i]; j <= m; j++)
dp[j] = max(dp[j], dp[j - c[i]] + w[i]);
printf ("%d\n", dp[m]);
return 0;
}
简单易懂,好评!