问题描述: 有一批集装箱要装上一艘载重量为c的轮船。其中集装箱i的重量为Wi。最优装载问题要求确定在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。
问题目标函数和约束条件如下图:
算法步骤如下:
①按重量升序排序
②装载货物
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)。