背包问题求具体方案

AcWing-12-背包问题求具体方案open in new window

实现

#include <iostream>
using namespace std;

const int N = 1010;
struct node {
    int v, w;
};
int n, m;
node a[N];
int f[N][N];

int main () {
    cin >> n >> m;
    for (int i = 1; i <= n; ++ i) cin >> a[i].v >> a[i].w;

    for (int i = n; i >= 1; -- i) {
        int v = a[i].v, w = a[i].w;
        for (int j = 0; j <= m; ++ j) {
            f[i][j] = f[i + 1][j];
            if (j >= v) f[i][j] = max(f[i][j], f[i + 1][j - v] + w);
        }
    }

    int j = m;
    for (int i = 1; i <= n; ++ i) {
        int v = a[i].v, w = a[i].w;
        if (j >= v && f[i][j] == f[i + 1][j - v] + w) {
            cout << i << ' ';
            j -= v;
        }
    }
    return 0;
}
最后修改于: