裝載問題-貪心算法

        現有一個載重爲W的貨船,集裝箱i個,重量分別爲wi,在不考慮體積的情況下,要求裝載的數量最多。

        這是一個簡單的最優裝載問題,類似01揹包問題,但考慮的不是價值而是數量,所以每次選取剩餘集裝箱中重量最輕的就可以,通過貪心算法就能得到最優解。

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by saishangmingzhu on 2018/11/30.
 */
public class BinPackingProblem {
    public static void main(String[] arg) {
        new BinPackingProblem().greedy();
    }

    /**
     * 貪心算法
     */
    public void greedy(){
        int rucksackWeight=10;
        List<Integer> goodsList=new ArrayList<>();
        goodsList.add(1);
        goodsList.add(3);
        goodsList.add(7);
        goodsList.add(3);
        goodsList.add(1);
        goodsList.add(5);
        goodsList.add(4);
        Collections.sort(goodsList);
        int surplus=rucksackWeight;
        List<Integer> resultGoodsList=new ArrayList<>();
        for (Integer goods:goodsList){
            if (surplus>=goods.intValue()){
                surplus=surplus-goods.intValue();
                resultGoodsList.add(goods);
            }
        }
        System.out.println(resultGoodsList.size());
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章