贪心算法-4.3最优装载问题

问题描述: 有一批集装箱要装上一艘载重量为c的轮船。其中集装箱i的重量为Wi。最优装载问题要求确定在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。
问题目标函数约束条件如下图:
1

算法步骤如下:

①按重量升序排序
②装载货物

public class test4_3 {
    public static float loading(float c,float[] w,int[] x){
        int n = w.length;
        Element2[] d = new Element2[n];
        //1.按重量升序排序
        for(int i=0;i<n;i++)
            d[i] = new Element2(w[i],i);
        bobleSort(d);
        //2.装载
        float opt = 0;
        for(int i=0;i<n;i++) x[i] = 0; //初始化x[i]
        for(int i=0;i<n&&d[i].w<=c;i++){
            x[i] = 1;
            opt += d[i].w;
            c -= d[i].w;
        }
        return opt;
    }
    //冒泡升序排序
    public static void bobleSort(Element2[] d){
        int n = d.length;
        Element2 temp;
        for(int i=0;i<n-1;i++){
            boolean ok = true;
            for(int j=1;j<n-i;j++){
                if(d[j-1].w>d[j].w){
                    temp = d[j];
                    d[j] = d[j-1];
                    d[j-1] = temp;
                    ok = false;
                }
            }
            if(ok) break;
        }
    }   
    public static void main(String[] args) {
        float[] w = {10,10,20,30};
        float c = 50;
        int[] x = new int[w.length];
        float load = loading(c,w,x);
        int count=0;
        for(int i=0;i<w.length;i++) count += x[i]; 
        System.out.println("载重量为"+c+"的轮船最多能装载"+count+"个集装箱,装载总重量为:"+load);
    }
}
class Element2{
    float w;
    int i;
    public Element2(float ww,int ii){
        this.w = ww;
        this.i = ii;
    }
}

运行结果如下:

载重量为50.0的轮船最多能装载3个集装箱,装载总重量为:40.0

总结:算法loading的主要计算量在于将集装箱依其重量从小到大排序,故算法所需的计算时间为 O(nlogn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SL_World

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值