帮本蒟蒻看看吧
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, W;
cin >> n;
vector<int> w(n);
for (int i = 0; i < n; i++) {
cin >> w[i];
}
cin >> W;
vector<vector<int> > table(n+1, vector<int>(W+1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= W; j++) {
if (w[i-1] > j) {
table[i][j] = table[i-1][j];
} else {
table[i][j] = max(w[i-1] + table[i-1][j-w[i-1]], table[i-1][j]);
}
}
}
int max_weight = table[n][W];
cout << max_weight << endl;
vector<int> items;
int i = n, j = W;
while (i > 0 && j > 0) {
if (table[i][j] == table[i-1][j]) {
i--;
} else {
items.push_back(i);
j -= w[i-1];
i--;
}
}
int num_items = items.size();
cout << num_items << endl;
for (int i = num_items-1; i >= 0; i--) {
cout << items[i] << " ";
}
cout << endl;
return 0;
}
请大家们提提修改意见,主要是内存超限,帮我看看吧!