7-9 装箱问题

发布时间 2023-12-23 22:00:33作者: qing影

7-9 装箱问题

假设有N项物品,大小分别为s1、s2、…、si、…、sN,其中si为满足1si≤100的整数。要把这些物品装入到容量为100的一批箱子(序号1-N)中。装箱方法是:对每项物品, 顺序扫描箱子,把该物品放入足以能够容下它的第一个箱子中。请写一个程序模拟这种装箱过程,并输出每个物品所在的箱子序号,以及放置全部物品所需的箱子数目。

输入格式:

输入第一行给出物品个数N 1000);第二行给出N个正整数si(1si≤100,表示第i项物品的大小)。

输出格式:

按照输入顺序输出每个物品的大小及其所在的箱子序号,每个物品占1行,最后一行输出所需的箱子数目。

输入样例:

8
60 70 80 90 30 40 10 20

输出样例:

60 1
70 2
80 3
90 4
30 1
40 5
10 1
20 2
5

简化版代码

解释:代码中的ans = ans > j ? ans : j;​利用了三元表达式,可以写作:if (ans < j) ans = j;

#include <iostream>

const int N = 1010;
int w[N], s, n, ans = 0;

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &s);
        for (int j = 1; j <= n; ++j) {
            if (w[j] + s > 100) continue;
            w[j] += s;
            printf("%d %d\n", s, j);
            ans = ans > j ? ans : j;
            break;
        }
    }
    printf("%d\n", ans);
  
    return 0;
}

注释版代码

#include <iostream>

const int N = 1010;
int w[N], s, n, ans = 0;

int main()
{
    // 输入物品的数量
    scanf("%d", &n);

    // 遍历每个物品
    for (int i = 1; i <= n; ++i) {
        // 输入物品的重量
        scanf("%d", &s);

        // 在背包中找到合适的位置放置物品
        for (int j = 1; j <= n; ++j) {
            // 如果放置该物品后不会超过重量限制
            if (w[j] + s > 100) continue;

            // 放置物品并输出
            w[j] += s;
            printf("%d %d\n", s, j);

            // 更新当前物品的放置位置
            ans = ans > j ? ans : j;

            // 跳出内层循环
            break;
        }
    }

    // 输出放置完所有物品后的最大层数
    printf("%d\n", ans);

    return 0;
}

java版代码

解释:代码中的ans = Math.max(ans, j);​利用了取最大值的写法,也可以用if (ans < j) ans = j;​的写法

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 输入物品的数量
        int n = scanner.nextInt();

		int[] w = new int[n + 1];
		int ans = 0;

        // 遍历每个物品
        for (int i = 1; i <= n; ++i) {
            // 输入物品的重量
            int s = scanner.nextInt();

            // 在背包中找到合适的位置放置物品
            for (int j = 1; j <= n; ++j) {
                // 如果放置该物品后不会超过重量限制
                if (w[j] + s > 100) continue;

                // 放置物品并输出
                w[j] += s;
                System.out.println(s + " " + j);

                // 更新当前物品的放置位置
                ans = Math.max(ans, j);

                // 跳出内层循环
                break;
            }
        }

        // 输出放置完所有物品后的最大层数
        System.out.println(ans);
    }
}