AcWing 12. 背包问题求具体方案

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

const int N = 1010;

int f[N][N];
int v[N],w[N];
int main() {
    int n,m;
    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) {
            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]);
        }
    }
    int vol = m; 
    for(int i = 1; i <= n; ++ i) {
        if(vol >= v[i] && f[i][vol] == f[i + 1][vol - v[i]] + w[i]) {
            cout << i << " ";
            vol -= v[i];
        }
    }
    return 0;
}
posted @ 2022-02-27 17:28  lemonsbiscuit  阅读(32)  评论(0编辑  收藏  举报