//贪婪算法实现装箱操作
public class test {
public static void main(String args[]) {
huowu[] h = new huowu[5];
h[0] = new huowu(10);
h[1] = new huowu(80);
h[2] = new huowu(50);
h[3] = new huowu(50);
h[4] = new huowu(20);
test t1 = new test();
t1.PutThehuowu(h);
}
// 装箱函数
public void PutThehuowu(huowu[] h) {
//将货物降序排列
for (int i = 0; i < h.length; i++) {
for (int j = i+1; j < h.length; j++) {
if(h[i].size<h[j].size){
huowu w=h[i];
h[i]=h[j];
h[j]=w;
}
}
}
int num = 1;
Box box =null;
for (int i = 0; i < h.length; i++) {
//是否装箱完毕
if(box==null){
box=new Box();
box.num=num++;
}
boolean isok=false;
Box currentBox = box;
Box lastBox = null;
while (currentBox != null) {
if(currentBox.next==null){
lastBox=currentBox;
}
if (h[i].size <= currentBox.size) {
// 将容量减少
currentBox.size -= h[i].size;
if (currentBox.huowufrist == null) {
//第一次装箱
currentBox.huowufrist = h[i];
} else {
huowu l = currentBox.huowufrist;
huowu last=null;
while (l != null) {
if(l.next==null){
last=l;
}
l = l.next;
}
// 将其加入货物链中
last.next = h[i];
break;
}
isok=true;
} else {
currentBox = currentBox.next;
}
}
// 当所有的箱子都装不下时再新建一个箱子
if (currentBox == null&&lastBox!=null&&!isok) {
Box nBox = new Box();
nBox.num = num++;
nBox.size -= h[i].size;
nBox.huowufrist = h[i];
lastBox.next = nBox;
}
}
// 输出
while (box != null) {
System.out.println("箱子编号:" + box.num);
System.out.println("货物:");
huowu i = box.huowufrist;
while (i != null) {
System.out.print(i.size + " ");
i = i.next;
}
box = box.next;
System.out.println();
}
}
}
// 箱子
class Box {
// 总容量
final int allsize = 100;
// 剩余的容量
int size = allsize;
// 储存的货物
huowu huowufrist = null;
// 箱子的编号
int num;
// 下一个箱子
Box next;
}
// 货物
class huowu {
public huowu(int size) {
this.size = size;
}
// 货物的容量
int size;
// 装箱时一起的箱子
huowu next = null;
}
贪婪算法实现装箱
最新推荐文章于 2024-08-05 14:49:17 发布