背包问题-最大值-空间恰好是j

背包问题-最大值-空间恰好\(j\)

一、\(01\)背包

求价值最大值:初始化\(f[0][0] = 0\), 其余是\(-INF\)

例子:给你一堆物品,每个物品有一定的体积和对应的价值,每个物品只能选一个,求 总体积恰好是\(j\)最大价值

输入

4 5
1 2
2 4
3 4
4 5

输出

8

1、二维

#include <bits/stdc++.h>

using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;

int n, m;
int f[N][N];

int main() {
    //文件输入
    freopen("QiaHao_01_Max.in", "r", stdin);
    scanf("%d %d", &n, &m);
    memset(f, -INF, sizeof f);
    f[0][0] = 0;

    for (int i = 1; i <= n; i++) {
        int v, w;
        scanf("%d %d", &v, &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);
        }
    }
    printf("%d\n", f[n][m]);
    return 0;
}

2、一维

#include <bits/stdc++.h>

using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;

int n, m;
int f[N];

int main() {
    //文件输入
    freopen("QiaHao_01_Max.in", "r", stdin);
    scanf("%d %d", &n, &m);

    memset(f, -INF, sizeof f);
    f[0] = 0;

    for (int i = 1; i <= n; i++) {
        int v, w;
        scanf("%d %d", &v, &w);
        for (int j = m; j >= v; j--)
            f[j] = max(f[j], f[j - v] + w);
    }
    printf("%d\n", f[m]);
    return 0;
}

二、完全背包

求价值最大值:初始化\(f[0][0] = 0\), 其余是\(-INF\)

例子:给你一堆物品,每个物品有一定的体积和对应的价值,每个物品可以选无数多个,求 总体积恰好是\(m\)最大价值

输入

4 5
1 2
2 4
3 4
4 5

输出

10

1、二维

#include <bits/stdc++.h>

using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;

int n, m;
int f[N][N];

int main() {
    cin >> n >> m;

    memset(f, -INF, sizeof f);
    f[0][0] = 0;

    for (int i = 1; i <= n; i++) {
        int v, w;
        cin >> v >> 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][j - v] + w);
        }
    }
    cout << f[n][m] << endl;
    return 0;
}

2、一维

#include <bits/stdc++.h>

using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;

int n, m;
int f[N];

int main() {
    //文件输入
    freopen("QiaHao_WQ_Max.in", "r", stdin);
    scanf("%d %d", &n, &m);

    memset(f, -INF, sizeof f);
    f[0] = 0;

    for (int i = 1; i <= n; i++) {
        int v, w;
        scanf("%d %d", &v, &w);
        for (int j = v; j <= m; j++)
            f[j] = max(f[j], f[j - v] + w);
    }
    printf("%d\n", f[m]);
    return 0;
}
posted @ 2022-01-27 09:41  糖豆爸爸  阅读(111)  评论(0编辑  收藏  举报
Live2D