01背包问题 二维
#include <bits/stdc++.h>
using namespace std;
int n, bagweight;
void solve() {
vector<int> weight(n, 0);
vector<int> value(n, 0);
for(int i = 0; i < n; ++i) {
cin >> weight[i];
}
for(int j = 0; j < n; ++j) {
cin >> value[j];
}
vector<vector<int>> dp(n, vector<int>(bagweight+1));
for (int i=0; i<n; i++){
dp[i][0]=0;
}
for (int j=0; j<bagweight+1; j++){
if (j>=weight[0]){
dp[0][j]=value[0];
}
}
for (int i=0; i<n; i++){
for (int j=0; j<bagweight+1; j++){
cout << dp[i][j] <<" ";
}
cout << endl;
}
cout << endl;
for (int i=1; i<n; i++){
for (int j=1; j<bagweight+1; j++){
if (j-weight[i]<0) dp[i][j] = dp[i-1][j];
else dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]);
}
}
for (int i=0; i<n; i++){
for (int j=0; j<bagweight+1; j++){
cout << dp[i][j] <<" ";
}
cout << endl;
}
cout << endl;
cout<<dp[n-1][bagweight];
}
int main() {
while(cin >> n >> bagweight) {
solve();
}
return 0;
}
46. 携带研究材料
#include <iostream>
#include <vector>
using namespace std;
int main() {
int M, N;
cin >> M >> N;
vector<int> costs(M);
vector<int> values(M);
for (int i = 0; i < M; i++) {
cin >> costs[i];
}
for (int j = 0; j < M; j++) {
cin >> values[j];
}
vector<int> dp(N + 1, 0);
for (int i=0; i<M; i++){
for (int j=N; j>=costs[i]; j--){
dp[j] = max(dp[j-1], dp[j-costs[i]]+values[i]);
cout << "dp[" << j <<"] = " << dp[j] << " ";
}
}
cout << endl;
cout << endl;
for (int i=0; i<dp.size(); i++){
cout << dp[i] << " ";
}
cout << endl;
cout << dp[N];
return 0;
}