AcWing 12. 背包问题求具体方案
原题链接
中等
作者:
天空与海洋之间
,
2020-10-11 15:25:44
,
所有人可见
,
阅读 353
#include <iostream>
using namespace std;
const int N = 1010,V = N;
int n,m;
int v[N],w[N];
int f[N][V];
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> v[i] >> w[i];
}
for(int j = 0; j <= m; j++){
f[n+1][j] = 0;
}
//倒着更新
for(int i = n; i >= 1; i--){
for(int j = 0; j <= m; j++){
f[i][j] = f[i+1][j];
if(j >= v[i]){
f[i][j] = max(f[i][j],f[i+1][j-v[i]] + w[i]);
}
}
}
//max_w = f[1][m];
int cur_v = m;
//正着推
for(int i = 1; i <= n; i++){
if(cur_v >= v[i] && f[i][cur_v] == f[i+1][cur_v-v[i]] + w[i]){
cout << i << " ";
cur_v -= v[i];
}
}
return 0;
}