0-1背包问题(回溯法)
来源:互联网 发布:第三方软件测试服务 编辑:程序博客网 时间:2024/05/16 11:42
1. 0-1背包问题
在0 / 1背包问题中,需对容量为c 的背包进行装载。从n 个物品中选取装入背包的物品,每件物品i 的重量为wi ,价值为pi 。
对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。
本题采用回溯法进行求解:
代码如下:
public class Package {
/** * @param args */private int num=10;int[] W={19,23,12,34,24,34,56,24,53,35}; //背包重量int[] V={57,68,87,17,12,21,31,42,14,15}; //背包权值private int[] a=new int[10];int C=300;static int MaxValue=0; //背包背的最大权值public static void main(String[] args) { // TODO Auto-generated method stub Package p=new Package(); p.ReadData(); p.Search(0); PrintMaxValue();}public void ReadData(){ for(int i=0;i<num;i++){ System.out.println("弟"+i+"的重量和价值是:"+W[i]+" "+V[i]); }}public void Search(int m){ if(m>=num){ CheckMax(); } else { a[m]=0; Search(m+1); a[m]=1; Search(m+1); }}public void CheckMax(){ int Weight=0; int Value=0; for(int i=0;i<num;i++){ //判断是否到达上限 if(a[i]==1){ Weight=Weight+W[i]; Value=Value+V[i]; } } if(Weight<=C){ if(Value>MaxValue){ MaxValue=Value; System.out.println("最大价值是:"+MaxValue); } }}public static void PrintMaxValue(){ System.out.println(" 最终的最大价值是:"+MaxValue);}}
0 0
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0/1背包问题-回溯法
- 回溯法:0-1背包问题
- 回溯法求解0/1背包问题
- 回溯法求解0-1背包问题
- 回溯法 0-1背包问题
- 回溯法解决0-1背包问题
- 回溯法之0-1背包问题
- 【回溯法】0-1背包问题
- 0-1背包问题回溯法
- 0-1背包问题---回溯法
- 回溯法解决0-1背包问题
- 0-1背包问题(回溯法)
- GPS坐标换算为百度坐标
- 【配置属性】—Entity Framework实例详解(DataAnnotations and Fluent API)
- Cxf Webservice安全认证
- 英伟达机器学习5大网红GPU卡
- SVN错误:Attempted to lock an already-locked dir
- 0-1背包问题(回溯法)
- android中对/data/data/<package name>/files下文件的读写操作
- Spring Boot下无法加载主类 org.apache.maven.wrapper.MavenWrapperMain问题解决
- 利用python进行数据分析-pandas入门
- 基于mina框架的GPS设备与服务器之间的交互
- 分析了443个免费代理 其中只有21%没有黑幕 那么剩下的79%呢
- 转:选择Linux入门教程的三个原则
- Redis的一些知识
- spring+jedis配置问题