欢迎来到天天文库
浏览记录
ID:34499006
大小:234.10 KB
页数:18页
时间:2019-03-07
《贪心算法java实现代码》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、贪心算法背包问题java代码packagetxsf;importjava.util.*;publicclassBag{publicintgetCapacity(){returncapacity;}publicvoidsetCapacity(intcapacity){this.capacity=capacity;}publicfloatgetValue(){returnvalue;}publicvoidsetValue(floatvalue){this.value=value+this.value;}priva
2、teintcapacity;//背包容量privatefloatvalue;//背包内价值privateRandomrand;publicBag(){//自动生成背包rand=newRandom();capacity=rand.nextInt(150);if(capacity<50){capacity+=rand.nextInt(70);}System.out.println("背包容量:"+capacity);value=0;}publicBag(intcapacity){//手工生成背包this.capa
3、city=capacity;System.out.println("背包容量:"+capacity);}publicfloatgetvalue(){returnvalue;}}/*abstractclassComputeItems{publicListlist=newArrayList();//public}*/classItems{privateStringimageStr;//物品名称privateintcapacity;//物品空间privateintvalue;//物品价值
4、privateRandomrand;publicItems(Strings){//自动生成物品rand=newRandom();this.imageStr=s;this.value=rand.nextInt(50)+1;this.capacity=rand.nextInt(50)+1;System.out.println(s+":"+this.capacity+""+this.value);}publicItems(Strings,intcapacity,intvalue){//手工生成物品this.imag
5、eStr=s;this.capacity=capacity;this.value=value;}publicfloatgetCapacity(){returnthis.capacity;}publicfloatgetValue(){returnthis.value;}publicStringgetimageStr(){returnthis.imageStr;}publicStringtoString(){return""+imageStr+":容量为:"+capacity+"价值为:"+value;}}int
6、erfaceCompute{float[]Sort();MapgetMap();}//重量优先计算classCapaimplementsCompute{privateListlist;privatefloat[]array;//排序物品权值privateMapmapItems;//哈希表,用来存放物品权值与物品publicCapa(Listlist){this.list=list;mapItems=newHashMap();array=newf
7、loat[list.size()];}publicfloat[]Sort(){inti=0;for(Itemsitems:list){array[i++]=items.getCapacity();//将物品权重放入数组mapItems.put(items.getCapacity(),items);//将物品权重与物品对象放入map对象}Arrays.sort(array);//物品排序升序returnarray;}@OverridepublicMapgetMap(){//TODOAuto-generatedm
8、ethodstubreturnmapItems;}publicStringtoString(){return"重量优先";}}//价值优先计算classValueimplementsCompute{privateListlist;privatefloat[]array;privateMapmapItems;publicValue(Listlist){this.
此文档下载收益归作者所有