完全背包

原理

见《进阶指南》第277页。

模板题

AcWing-3-完全背包问题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];

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

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