今天用贪心算法给出背包问题的一种解,虽然贪心算法不一定是最优解,但是在数据量极大时,贪心算法可以快速获得接近最优解的答案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 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() {
public int compare(Goods g1,Goods g2)
{
if (g1.getWorth()>g2.getWorth())
return -1;
else if (g1.getWorth()
return 1;
else {
if (g1.getVolume()>g2.getVolume())
return 1;
else if (g1.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;
}
}