一维dp:
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
return x * f;
}
int t, m;
int p[1005], v[150], w[150];
int main() {
t = read(), m = read();
for (int i = 0; i < m; ++i) {
w[i] = read(), v[i] = read();
}
for (int i = 0; i < m; ++i) {
for (int j = t; j >= w[i]; --j) {
p[j] = max(p[j], p[j - w[i]] + v[i]);
}
}
cout << p[t] << endl;
return 0;
}
二维dp:
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
return x * f;
}
int t, m;
int p[1005][1005], v[150], w[150]; //一维表示用了前几个,二维表示重量
int main() {
t = read(), m = read();
for (int i = 1; i <= m; ++i) {
w[i] = read(), v[i] = read();
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= t; ++j) {
if (j < w[i]) {
p[i][j] = p[i - 1][j];
} else {
p[i][j] = max(p[i-1][j], p[i - 1][j - w[i]] + v[i]);
}
}
}
cout << p[m][t] << endl;
return 0;
}
本文通过两个具体的代码示例介绍了如何使用一维和二维动态规划解决背包问题。在一维DP中,我们通过迭代更新物品价值来求解最大价值;而在二维DP中,则是通过构造二维数组来记录不同物品组合下的最大价值。两种方法都有效地解决了背包问题,并展示了动态规划的基本思想。
1813

被折叠的 条评论
为什么被折叠?



