1. 程式人生 > >貪心法部分揹包問題的實現

貪心法部分揹包問題的實現

import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/11/29.
 */
public class Knapsack {

    public static void main(String [] args){
        double L =12;
        int[] V = {13,10,24,15,28,33,20,8};//存放價值
        int[] W = {2,1,3,2,4,5,3,1};//存放重量
        int len = V.length;

        double totalValue = 0;
        Listresult = new LinkedList<>();

        sort(V,W);//按單位價值排序
        for(int j = 0 ; j < len ; j++)
            System.out.println("物品"+(j+1)+": 價值為:"+ V[j]+" 重量為"+W[j] );


        int i ;
        boolean flag = false;//flag = false代表所有物品全部裝入,為true代表有物品部分裝入
        double share = 0 ;//部分裝入部分的份額.
        for(i=0;i=W[i]){//能把整個物品裝進去
                result.add(i);
                L -= W[i];
                totalValue += V[i];

            }else{
                double uniValue = V[i]/(double)W[i];
                totalValue += L*uniValue;
                share = L;
                flag = true;
                L=0;
                result.add(i);



            }
        }

        DecimalFormat de = new DecimalFormat("0.00");
       System.out.println("所選的結果為:");
        for(Integer r : result){
            System.out.print(r+1+" ");
        }
        System.out.println("總價值為"+de.format(totalValue));

        if(flag = true){
            System.out.println("最後一個物品為部分裝入,裝入的部分重量為"+share);

        }else {
            System.out.println("物品全部裝入");
        }



    }

    private static void sort(int[] p, int[] w) {
        int len = p.length;
        int tmp = 0;
        for(int i = 0 ; i < len - 1 ; i++){
            int maxIndex = i ;
            double IUniValue = p[i]/(double)w[i] ;
            for(int j = i+1 ; j < len ; j ++){
                double  JUniValue = p[j]/(double)w[j];
                if(JUniValue>IUniValue){
                    maxIndex = j ;
                }
            }
            tmp = p[i];
            p[i] = p[maxIndex];
            p[maxIndex] =tmp;
            tmp = w[i];
            w[i] = w[maxIndex];
            w[maxIndex] =tmp;
        }




    }
}