You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

##AcWing 1024. 装箱问题

一、题目描述

有一个箱子容量为 V,同时有 n 个物品,每个物品有一个体积(正整数)。

要求 n 个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。

输入格式 第一行是一个整数 V,表示箱子容量。

第二行是一个整数 n,表示物品数。

接下来 n 行,每行一个正整数(不超过10000),分别表示这 n 个物品的各自体积。

输出格式 一个整数,表示箱子剩余空间。

数据范围 0<V≤20000,0<n≤30

输入样例

24
6
8
3
12
7
9
7

输出样例

0

二、题目解析

1、注意mn的输入顺序 2、本题目没有w[]的概念,就是把v[]w[]看成一种东西。 3、最后问剩余体积最小而不是最大占用体积,需要m-f[m]即可。

三、二维数组写法

#include <bits/stdc++.h>
using namespace std;
const int N = 40, M = 10010;
int n, m;
int f[N][M * N];
int v[N];
int main() {
    cin >> m >> n;
    for (int i = 1; i <= n; i++) cin >> v[i];

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

四、一维数组写法

#include <bits/stdc++.h>

using namespace std;
const int N = 20010;

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

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

    // 01背包模板
    for (int i = 1; i <= n; i++)
        for (int j = m; j >= v[i]; j--)
            f[j] = max(f[j], f[j - v[i]] + v[i]);

    // 输出
    printf("%d", m - f[m]);
    return 0;
}