问题
代码1(二维数组)
#include <iostream>
#include<string>
using namespace std;
int dp[35][205];
int w[35], c[35];
int main() {
int m, n;
cin >> m >> n;
for (int i = 1;i <= n;i++) {
cin >> w[i] >> c[i];
}
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
//拿不下
if (j < w[i]) {
dp[i][j] = dp[i - 1][j];
}
//拿还是不拿
else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i]] + c[i]);
}
}
}
for (int i = 0;i <= n;i++) {
for (int j = 0;j <= m;j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}
return 0;
}
代码2(一维数组)
#include <iostream>
#include<string>
using namespace std;
int dp[205];
int w[35], c[35];
int main() {
int m, n;
cin >> m >> n;
for (int i = 1;i <= n;i++) {
cin >> w[i] >> c[i];
}
for (int i = 1;i <= n;i++) {
for (int j = m;j >= 1;j--) {
if (j >= w[i]) {
dp[j] = max(dp[j], dp[j - w[i]] + c[i]);
}
}
}
cout << dp[m] << " ";
return 0;
}