Java描述贪心算法解决背包问题
来源:互联网 发布:道路设计常用数据手册 编辑:程序博客网 时间:2024/05/16 08:21
思路: 首先将物品根据性价比排好序在一个集合里,性价比=价格/重量...
然后根据性价比从大到小依次依次放入背包,如果没办法放入这个物品的全部,就放入一部分,如果可以放入全量物品,就放入全量物品。
Main.java的代码
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;/** * Created by HuLuo on 2016/2/16. */public class Main{ //背包总质量 private static double M = 20; //物品数量 private static int number = 3; public static void main(String[] args) { MyObject myObject1 = new MyObject( 18, 25 ); MyObject myObject2 = new MyObject( 15, 24 ); MyObject myObject3 = new MyObject( 10, 15 ); ArrayList<MyObject> myObjects = new ArrayList<MyObject>( number ); myObject1.priceRatio = ( myObject1.price * 1.0 ) / ( myObject1.weight ); myObject2.priceRatio = ( myObject2.price * 1.0 ) / ( myObject2.weight ); myObject3.priceRatio = ( myObject3.price * 1.0 ) / ( myObject3.weight ); myObjects.add( myObject1 ); myObjects.add( myObject2 ); myObjects.add( myObject3 ); //根据物品的性价比将集合中的物品做一个排序 ,按照性价比从大到小排列 Collections.sort( myObjects, new Comparator<MyObject>() { @Override public int compare(MyObject o1, MyObject o2) { if(o1.priceRatio > o2.priceRatio) { return -1; } else return 1; } } ); MyObject temp = null; for(int i = 0; i < number && M > 0; i++) { temp = myObjects.get( i ); if(M >= temp.weight) { M = M - temp.weight; temp.x = 1.0; } else { temp.x = ( M * 1.0 ) / temp.weight; M = M - ( temp.weight * temp.x ); } } for(MyObject myObject : myObjects) { System.out.println( "物品价格是:" + myObject.price + "的物品, 装入比例是:" + myObject.x ); } }}
/** * Created by HuLuo on 2016/2/16. *//** * 物品对象 */public class MyObject{ public int weight = 0; public int price = 0; //装入的比例 public double x = 0; //性价比 public double priceRatio = 0 ; public MyObject(int weight, int price) { this.weight = weight; this.price = price; }}
1 0
- Java描述贪心算法解决背包问题
- [贪心算法]java解决背包问题
- 贪心算法解决背包问题
- 贪心算法解决背包问题
- 贪心算法解决背包问题
- 贪心算法解决部分背包问题
- 数据结构(C#)-- 贪心算法解决背包问题
- 贪心算法解决0 1背包问题
- 用贪心算法解决背包问题
- 用贪心算法背包问题,Java实现
- JAVA贪心算法实现背包问题
- Java解决算法-背包问题
- 贪心算法 - 背包问题
- 贪心算法----背包问题
- 【贪心算法】:背包问题
- 贪心算法-背包问题
- 贪心算法 背包问题
- 贪心算法-背包问题
- Smooth Follow
- 牙
- narnia4
- firefox 禁用javascript
- 博客,我来了~
- Java描述贪心算法解决背包问题
- NSTimer用法总结
- Spring Data JPA入门
- 如何通过后台代码获取map类型如下所示的数据:
- [2016.02.15]Leetcode刷题记录之Add Two Numbers
- MongoDB安装配置快速指南
- 无限循环背景ParallaxNode
- 不通过创建线程来实现函数间的同步
- poj 2887 Big String