回溯法法求解0-1背包问题实验

实验目的:
1) 掌握动回溯法的设计思想;
2)掌握回溯法解题步骤;
3)学习运用回溯法分析并解决0-1背包问题。
实验要求:运用回溯法分析并解决下表给定的0-1背包问题,5个物品重量分别是3,5,7,8,9和价值分别是4,6,7,9,10,求背包总价值最大问题
在这里插入图片描述

package 算法实验;
public class bag01 {
	int n = 5;
	int capacity = 20;
	int[] weight = {3,5,7,8,9};
	double[] value = {4,6,7,9,10};
	int maxValue = 0;
	int tempValue;
	int tempWeight;
	int[] way = new int[n];
	int[] bestWay = new int[n];
	public void BackTrack(int t){
		//已经搜索到根节点
		if(t>n-1){
			if(tempValue > maxValue){
				maxValue = tempValue;
				for(int i=0;i<n;i++)
					bestWay[i] = way[i];
			}
			return;
		}
		//搜索左边节点
		if(tempWeight + weight[t] <= capacity){
			tempWeight += weight[t];
			tempValue += value[t];
			way[t] = 1;
			BackTrack(t+1);
			tempWeight -= weight[t];
			tempValue -= value[t];
			way[t] = 0;
		}
		//不装入这个物品,直接搜索右边的节点
		if( Bound(t+1) >= maxValue){
			BackTrack(t+1);
		}
	}
	//用于计算剩余物品的最高价值上界
	public double Bound(int k){
		double maxLeft = tempValue;
		int leftWeight = capacity - tempWeight;
		//尽力依照单位重量价值次序装剩余的物品
		while(k <= n-1 && leftWeight > weight[k] ){
			leftWeight -= weight[k];
			maxLeft += value[k];
			k++;
		}
		//不能装时,用下一个物品的单位重量价值折算到剩余空间。
		if( k <= n-1){
			maxLeft += value[k]/weight[k]*leftWeight;
		}
		return maxLeft;
	}
	public static void main(String[] args){
		bag01 b = new bag01();
		b.BackTrack(0);
		System.out.println("该背包能够取到的最大价值为:"+b.maxValue);
		System.out.println("取出的方法为:");
		for(int i : b.bestWay)
			System.out.print(i+"  ");
	}
}

结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

青柠Löwenzahn m.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值