贪婪算法实现装箱

//贪婪算法实现装箱操作
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;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值