AcWing 12. 背包问题求具体方案
原题链接
中等
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m;
int dp[N][N], v[N], w[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for (int i = n; i >= 1; i--) {
for (int j = 0; j <= m; j++) {
dp[i][j] = dp[i + 1][j];
if (j >= v[i])
dp[i][j] = max(dp[i][j], dp[i + 1][j - v[i]] + w[i]);
}
}
int wei = m;
// 贪心求结果
for (int i = 1; i <= n; i++) {
// 要有判断wei >= v[i]
if (wei >= v[i] && dp[i][wei] == dp[i + 1][wei - v[i]] + w[i]) {
cout << i << " ";
// 满足才减
wei -= v[i];
}
}
return 0;
}