贪心算法Q3——01背包问题
问题描述:
有n件物品,每个物品都有一个大小和价值,给你一个固定容量的背包,要求装的东西价值总和最大
实例:
现在有重量分别为35 30 60 50 40 10 25,价值分别为10 40 30 50 35 40 30的物品,
背包最大承重为150,求该背包所能放置的物品最大价值是多少?
package 贪心;
public class Article {
public int weight,value;
public double valueOfDensity;
Article(int weight,int value){
this.weight=weight;
this.value=value;
this.valueOfDensity=value*1.0/weight;
}
@Override
public String toString() {
return "Article [weight=" + weight + ", value=" + value + ", valueOfDensity=" + valueOfDensity + "]";
}
}
package 贪心;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class _01背包问题 {
//传一个比较器Comparator<Article> cmp 按设定关键字排序
static void select(String title,Comparator<Article> cmp) {
//将物品变量直接封装在成员方法里作为局部变量 就可以不用通过mian方法传参了
Article [] articles=new Article[] {
new Article(35,10),new Article(30,40),
new Article(60,30),new Article(50,50),
new Article(40,35),new Article(10,40),
new Article(25,30)
};
Arrays.sort(articles, cmp);
//将Article类封装到list存储结构
List<Article> selectedArticles=new LinkedList<>();
int capacity=150,weight=0,value=0;
for(int i=0;i<articles.length&&weight<capacity;i++) {
int newWeight=weight+articles[i].weight;
if(newWeight<=capacity) {
weight=newWeight;
value+=articles[i].value;
selectedArticles.add(articles[i]);
}
}
for(int i=0;i<selectedArticles.size();i++) {
System.out.println(selectedArticles.get(i));
}
System.out.println(weight);
System.out.println(value);
}
public static void main(String[] args) {
//价值主导
select("价值主导",(Article a1,Article a2)->{
return a2.value-a1.value;
});
//重量主导
select("重量主导",(Article a1,Article a2)->{
return a1.weight-a2.weight;
});
//价值主导
//a2.valueOfDensity-a1.valueOfDensity;结果为double型 而迭代器要求返回类型为int
//Double.compare(double d1,doouble d2)返回int型
select("价值密度主导",(Article a1,Article a2)->{
return Double.compare(a2.valueOfDensity, a1.valueOfDensity);
});
}
}
动态规划版本见: