1. 程式人生 > >揹包問題(貪心java)

揹包問題(貪心java)

經過我不斷測試發現確實不是最優解 

package TX;


import java.util.Arrays;

public class GreedyPackage {
    public void greedyPackage(int maxWeight,int[] weight,int[] val) {
        int n=weight.length;
        //價效比的陣列
         double[] weightVal= new double[n];
         //按價效比存放i的陣列
        int[] index=new int[n];
        for (int i = 0; i <n ; i++) {
            weightVal[i]=val[i]/weight[i];
            index[i]=i;//開始順序
        }
        //按價效比進行排序 用降序排列
        for (int i = 0; i <n-1 ; i++) {
            for (int j = i+1; j <n ; j++) {
                if (weightVal[i]<weightVal[j]){
                    double temp=weightVal[i];
                    weightVal[i]=weightVal[j];
                    weightVal[j]=temp;
                    //交換下標
                    int ind=index[i];
                    index[i]=index[j];
                    index[j]=ind;
                }
            }
        }
        int[] x=new int[n];
        int maxval=0;
        for (int i = 0; i <n ; i++) {
            if (maxWeight>weight[index[i]]){
                x[i]=1;
                System.out.println(weight[index[i]]+"被放入揹包");
                maxWeight-=weight[index[i]];
                maxval+=val[index[i]];
            }
        }
        System.out.println(maxval);
            System.out.print(Arrays.toString(x));
    }
    public  static void main(String[] args){
        GreedyPackage a=new GreedyPackage();
        int [] wight={35,30,60,50,40,10,25};
        int[] val={10,40,30,50,35,40,30};
        a.greedyPackage(150,wight,val);
    }
}