贪心_01背包
package agrisom;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* 贪心算法求背包问题
*/
/**
* 物品类
*/
class Good{
public int weight; //重量
public int value; //价值
public int status; //选中标志
public String name; //货品名称
public float rate; //单价
}
public class BackPackGreedy {
public Good [] goods;
/**
* 物品初始化
*/
public void init(int [] weights,int [] values){
int length=weights.length;
this.goods=new Good[length];
for(int i=0;i<length;i++){
Good good=new Good();
goods[i]=good;
good.weight=weights[i];
good.value=values[i];
good.status=0;
good.name=(i+1)+"";
good.rate=(values[i]+0f)/weights[i];
}
this.print();
}
/**
* 打印物品状态
*/
public void print(){
String formatStr=" ";
DecimalFormat df=new DecimalFormat("##0.000");
for(int i=0;i<this.goods.length;i++){
Good good=goods[i];
System.out.print(good.name+formatStr);
System.out.print(good.weight+formatStr);
System.out.print(good.value+formatStr);
System.out.print(df.format(good.rate)+formatStr);
System.out.println(good.status+formatStr);
}
System.out.println();
}
/**
* 贪心策略:每次选取单位容量价值最大的物品
*/
public void greedy(int maxWeight){
int packWeight=0; //当前背包重量
int packValue=0; //当前背包价值
float maxRate=0f; //当前最大货品单价
int j=0,n=0;
String [] names=new String [this.goods.length]; //选择的物品数组
while(packWeight<maxWeight)
{
for(int i=0;i<this.goods.length;i++)
{
if(goods[i].rate>maxRate && goods[i].status==0)
{
maxRate=goods[i].rate;
j=i;
}
}
names[n++]=goods[j].name;
maxRate=0.0f;
goods[j].status=1;
if(packWeight+goods[j].weight<maxWeight){
packWeight=packWeight+goods[j].weight;
packValue=packValue+goods[j].value;
}else{
break;
}
}
this.print();
System.out.println("packWeight: "+packWeight+" packValue: "+packValue);
System.out.print("selected goods list: ");
for(int i=0;i<names.length;i++){
if(names[i]!=null){
System.out.print(names[i] + " ");
}
}
}
public static void main(String [] args){
int [] weights=new int[]{35,30,60,50,40,10,25};
int [] values=new int[]{10,40,30,50,35,40,30};
BackPackGreedy bpg=new BackPackGreedy();
bpg.init(weights, values);
bpg.greedy(150);
}
}
/**
运行结果:
1 35 10 0.286 0
2 30 40 1.333 0
3 60 30 0.500 0
4 50 50 1.000 0
5 40 35 0.875 0
6 10 40 4.000 0
7 25 30 1.200 0
1 35 10 0.286 0
2 30 40 1.333 1
3 60 30 0.500 0
4 50 50 1.000 1
5 40 35 0.875 1
6 10 40 4.000 1
7 25 30 1.200 1
packWeight: 115 packValue: 160
selected goods list: 6 2 7 4 5
*/