Java实例18 - 0-1背包放水果

 
/**
 * 0-1背包问题
 * 用贪婪法求解
 * 问题:有一组水果,他们的重量和价格如下所示,另有一背包可承受总重为14
 * 要求:只能全选或者不选某种水果将其放入背包,背包不能超重
 * 求解:找到使得该包中水果价值最高的放法
 */
package al;
public class Fruit {
	public final String name;
	public final double weight;
	public final double price;
	public final double maxWeight = 14;
	public static void main(String[] args) {
		//初始化数组
		Fruit[] fruits = {
				new Fruit("李子", 4, 4600), 
                new Fruit("苹果", 5, 5700), 
                new Fruit("橘子", 2, 2250), 
                new Fruit("草莓", 1, 1100), 
                new Fruit("甜瓜", 6, 6700)
				};
		
		Fruit f = new Fruit("", 0, 0);
		
		/**
		 * 基于pi/wi比率的贪婪算法
		 */
		f.sort1(fruits);
		f.solve(fruits);
		
		/**
		 * 基于wi的贪婪算法
		 */
		f.sort2(fruits);
		f.solve(fruits);	
		
		
	}
	//构造函数
	public Fruit(String name, double weight, double price) {
		this.name = name;
		this.weight = weight;
		this.price = price;
	}
	
	//按pi/wi排序
	public void sort1(Fruit[] array) {
		int i, j;
		Fruit tmp = new Fruit("", 0, 0);
		for (i = 0; i <= (array.length - 1); i++) { // outer loop
			for (j = 0; j < (array.length - 1 - i); j++) { // inner loop
				if (array[j].price/array[j].weight < array[j + 1].price/array[j+1].weight) {
					tmp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = tmp;
				}
			}
		}
	}
	
	//按wi排序
	public void sort2(Fruit[] array) {
		int i, j;
		Fruit tmp = new Fruit("", 0, 0);
		for (i = 0; i <= (array.length - 1); i++) { // outer loop
			for (j = 0; j < (array.length - 1 - i); j++) { // inner loop
				if (array[j].weight < array[j+1].weight) {
					tmp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = tmp;
				}
			}
		}
	}
	
	//贪婪法求解,轮询数组,每次选则不超重并且局部最优的值
	public void solve(Fruit[] fruits) {			
		double currentWeight = 0;
		double currentPrice = 0;
		
		for(int i=0; i< fruits.length; i++) {			
			if (currentWeight + fruits[i].weight <= this.maxWeight) {
				currentWeight += fruits[i].weight;
				currentPrice += fruits[i].price;
				System.out.println("Put "+fruits[i].name+ " into pack, current weight is " +  
						currentWeight+", current price is "+currentPrice);
				
			}
		}
		System.out.println("---------------------------------------");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值