背包容量M=8;
物品效益值(P1,P2,P3,P4,P5,P6)=(10,18,40,56,30,15); (W1,W2,W3,W4,W5,W6)=(1,2,5,8,5,3);
P1/W1>P2/W2>P3/w3>P4/W4>P5/W5>P6/W6
P,W分别用一个数组表示,返回解序列X。
1 package greedy; 2 3 public class GREEDYKNAPSACK { 4 double M; 5 double[] P,W; 6 int n=6; 7 double[] X=new double[n]; 8 GREEDYKNAPSACK(){ 9 M=9; 10 double[] temp0={10,18,40,56,30,15}; 11 P=temp0; 12 double[] temp1={1,2,5,8,5,3}; 13 W=temp1; 14 X=greedyKnapsack(P,W,M,X,n); 15 for(int i=0;i<n;i++){ 16 System.out.print(X[i]+" "); 17 } 18 } 19 public double[] greedyKnapsack(double[] P,double[] W,double M,double[] X,int n){ 20 double Cu=M; 21 int i; 22 L1: for(i=0;i<n;i++){ 23 if(W[i]>Cu){ 24 break L1; 25 } 26 Cu=Cu-W[i]; 27 X[i]=1; 28 } 29 if(i<n){ 30 X[i]=Cu/W[i]; 31 } 32 return X; 33 } 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 new GREEDYKNAPSACK(); 37 } 38 39 }