跳到正文

算法·理论

一维01背包模板

wangbinfeng约 1 分钟
原文
文章信息与版本

文章信息

发布
2020年11月15日
收录
2026年11月10日
更新
2026年11月18日
篇幅
约 1 分钟

版本

  1. v1当前

引用自:一本通 1267:【例9.11】01背包问题

C++
#include <iostream>
#include <cstdio>
using namespace std;
//Mystery_Sky
//一维01背包模板 
#define M 1000
int f[M], c[M], w[M];
int ans, v, m;
int main() {
    scanf("%d%d", &v, &m);
    for(int i = 1; i <= m; i++) scanf("%d%d", &c[i], &w[i]);
    for(int i = 1; i <= m; i++)
        for(int j = v; j >= c[i]; j--) {
            f[j] = max(f[j], f[j-c[i]]+w[i]);
        }
    printf("%d\n", f[v]);
    return 0;
}
原文