那个背包装骨头的题目,原题不重要
主要是一个应该注意的bug:物品的重量可能是0
本来应该早就学会的题目,唉。学了就不晚
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int maxweight = 1005;
const int maxnum = 1005;
int dp[maxnum][maxweight];
struct food {
int weight, money;
bool operator<(food b) {
return weight < b.weight;
}
} f[maxnum];
int n, m;
void solve() {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 0; j <= m; j++) { //可能有体积0的物品,不能从1开始循环
if (j >= f[i].weight) {
dp[i][j] = max(dp[i - 1][j - f[i].weight] + f[i].money, dp[i - 1][j]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
}
int main() {
#ifdef LOCAL
freopen("zz_in.txt", "r", stdin);
freopen("zz_op.txt", "w", stdout);
#endif
int t, i, j, k;
cin >> t;
while (t--) {
memset(dp, 0, sizeof(dp));
cin >> n >> m;
for (i = 1; i <= n; i++) {
cin >> f[i].money;
}
for (i = 1; i <= n; i++) {
cin >> f[i].weight;
}
solve();
cout << dp[n][m] << endl;
//dp数组已经存的最优解了,没必要再找一次
}
#ifdef LOCAL
printf("Time used = %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
return 0;
}
豪华升级成滚动数组(一维数组)
需要注意:倒着循环
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int maxweight = 1005;
const int maxnum = 1005;
// int dp[maxnum][maxweight];
int dp[maxweight];
struct food {
int weight, money;
bool operator<(food b) {
return weight < b.weight;
}
} f[maxnum];
int n, m;
void solve() {
int i, j;
// for (i = 1; i <= n; i++) {
// for (j = 0; j <= m; j++) { //可能有体积0的物品,不能从1开始循环
// if (j >= f[i].weight) {
// dp[i][j] = max(dp[i - 1][j - f[i].weight] + f[i].money, dp[i - 1][j]);
// } else {
// dp[i][j] = dp[i - 1][j];
// }
// }
// }
for (i = 1; i <= n; i++) {
for (j = m; j >= 0; j--) { //倒着循环,防止需要用到的上一个数组的数据被覆盖
if (j >= f[i].weight) {
dp[j] = max(dp[j - f[i].weight] + f[i].money, dp[j]);
}
}
}
}
int main() {
#ifdef LOCAL
freopen("zz_in.txt", "r", stdin);
freopen("zz_op.txt", "w", stdout);
#endif
int t, i, j, k;
cin >> t;
while (t--) {
memset(dp, 0, sizeof(dp));
cin >> n >> m;
for (i = 1; i <= n; i++) {
cin >> f[i].money;
}
for (i = 1; i <= n; i++) {
cin >> f[i].weight;
}
solve();
// cout << dp[n][m] << endl;
// //dp数组已经存的最优解了,没必要再找一次
cout << dp[m] << endl;
}
#ifdef LOCAL
printf("Time used = %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
return 0;
}