1. 程式人生 > >0-1揹包問題-貪心演算法

0-1揹包問題-貪心演算法

    今天用貪心演算法給出揹包問題的一種解,雖然貪心演算法不一定是最優解,但是在資料量極大時,貪心演算法可以快速獲得接近最優解的答案

package test;

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

/**
 * Created by saishangmingzhu on 2018/11/26.
 */
public class Rucksack {
    //【1】輸入揹包容量
    //【2】輸入物品體積及價值
    public static void main(String[] arg) {
        new Rucksack().greedy();
    }

    /**
     * 貪心演算法
     */
    public void greedy(){
        int rucksackV=10;
        List<Goods> goodsList=new ArrayList<>();
        goodsList.add(new Goods("書",1,2));
        goodsList.add(new Goods("足球",3,4));
        goodsList.add(new Goods("大箱子",7,2));
        goodsList.add(new Goods("macbook",3,6));
        goodsList.add(new Goods("iphone",1,5));
        goodsList.add(new Goods("禮盒",5,3));
        goodsList.add(new Goods("小箱子",4,2));
        //排序,價值大的排前邊,相同情況下體積小的排前邊
        Collections.sort(goodsList,new Comparator<Goods>() {
            public int compare(Goods g1,Goods g2)
            {
                if (g1.getWorth()>g2.getWorth())
                    return -1;
                else if (g1.getWorth()<g2.getWorth())
                    return 1;
                else {
                    if (g1.getVolume()>g2.getVolume())
                        return 1;
                    else if (g1.getVolume()<g2.getVolume())
                        return -1;
                    return 0;
                }
            }
        });
        int surplusV=rucksackV;
        int maxW=0;
        for (Goods goods:goodsList){
            if (goods.getVolume()<=surplusV){
                surplusV=surplusV-goods.getVolume();
                maxW=maxW+goods.getWorth();
            }
        }
        System.out.print(maxW);
    }
}
class Goods{
    private String name;
    private int volume;
    private int worth;

    public Goods(){}
    public Goods(String n,int v,int w){
        this.name=n;
        this.volume=v;
        this.worth=w;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public int getWorth() {
        return worth;
    }

    public void setWorth(int worth) {
        this.worth = worth;
    }
}