Java描述貪心演算法解決揹包問題
阿新 • • 發佈:2019-02-09
思路: 首先將物品根據價效比排好序在一個集合裡,價效比=價格/重量...
然後根據價效比從大到小依次依次放入揹包,如果沒辦法放入這個物品的全部,就放入一部分,如果可以放入全量物品,就放入全量物品。
Main.java的程式碼
MyObject.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; } }