欢迎来到天天文库
浏览记录
ID:33422484
大小:234.10 KB
页数:18页
时间:2019-02-25
《贪心算法java 实现代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、贪心算法背包问题java代码packagetxsf;importjava.util.*;publicclassBag{publicintgetCapacity(){returncapacity;}publicvoidsetCapacity(intcapacity){this.capacity=capacity;}publicfloatgetValue(){returnvalue;}publicvoidsetValue(floatvalue){this.value=value+this.value;}privateintcapacity;//背包容量
2、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.capacity=capacity;System.out.println("背包容量:"
3、+capacity);}publicfloatgetvalue(){returnvalue;}}/*abstractclassComputeItems{publicListlist=newArrayList();//public}*/classItems{privateStringimageStr;//物品名称privateintcapacity;//物品空间privateintvalue;//物品价值privateRandomrand;publicItems(Strings){//自动生成物品rand=newRando
4、m();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.imageStr=s;this.capacity=capacity;this.value=value;}publicfloatgetCapacity(){returnt
5、his.capacity;}publicfloatgetValue(){returnthis.value;}publicStringgetimageStr(){returnthis.imageStr;}publicStringtoString(){return""+imageStr+":容量为:"+capacity+"价值为:"+value;}}interfaceCompute{float[]Sort();MapgetMap();}//重量优先计算classCapaimplementsCompute{privateListlist;p
6、rivatefloat[]array;//排序物品权值privateMapmapItems;//哈希表,用来存放物品权值与物品publicCapa(Listlist){this.list=list;mapItems=newHashMap();array=newfloat[list.size()];}publicfloat[]Sort(){inti=0;for(Itemsitems:list){array[i++]=items.getCapacity();//将物品权重放入数组mapItems.pu
7、t(items.getCapacity(),items);//将物品权重与物品对象放入map对象}Arrays.sort(array);//物品排序升序returnarray;}@OverridepublicMapgetMap(){//TODOAuto-generatedmethodstubreturnmapItems;}publicStringtoString(){return"重量优先";}}//价值优先计算classValueimplementsCompute{privateListlist;privatefloat[]arra
8、y;privateMapmapItems;publicValue(Listlist){this.
此文档下载收益归作者所有