前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最优装载问题

最优装载问题

作者头像
我没有三颗心脏
发布2018-04-26 16:17:06
1.2K0
发布2018-04-26 16:17:06
举报
文章被收录于专栏:Java WebJava Web

问题描述:

有一批集装箱要装上一艘载重量为c的轮船。其中集装箱i的重量为Wi。最优装载问题要求确定在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。

问题可以描述为:

式中,变量xi = 0 表示不装入集装箱 i,xxi = 1 表示装入集装箱 i。

刚看到的时候,给我的感觉就像是排好序的背包问题一样,那么问题就变得简单了。

代码实现:

为了不改变原weight数组中的顺序,所以在函数中引入了一个临时变量tempWeight来进行冒泡排序。

代码语言:javascript
复制
private static void load_problem(int[] weight, int c) {
    int number = weight.length;     // 商品数量
    int[] tempWeight = weight;      // 临时数组用于排序
    int currentSpace = c;           // 剩余空间

    // 冒泡排序:从小到大排序
    for (int i = 0; i < number; i++) {
        for (int j = i + 1; j < number; j++) {
            if (tempWeight[i] > tempWeight[j]) {
                tempWeight[i] = tempWeight[i] + tempWeight[j];
                tempWeight[j] = tempWeight[i] - tempWeight[j];
                tempWeight[i] = tempWeight[i] - tempWeight[j];
            }
        }   // end inner for
    }   // end outer for

    System.out.println("装载物品如下:");
    // 贪心选择装载
    for (int i = 0; i < number; i++) {
        if (tempWeight[i] > currentSpace) break;

        currentSpace -= tempWeight[i];
        System.out.printf("重量为:%2d\n", tempWeight[i]);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题描述:
  • 代码实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档