1、问题简述
略
2、背包问题思想
①按(v1/w1)≥(v2/w2)≥…(vn/wn)排序
②依次放入物品,直至放满。
③注意,物品可以放部分,不一定得全部放,这是区别0-1背包问题的关键。
三、代码实现(java)
public class bag {
public static void Bag(float[] weight, float[] value, int capacity, int number, float[] percent) {
float c = capacity;
int i = 0;
for (i = 0; i < number; i++) {
if (weight[i] > c)
break;
else {
percent[i] = 1;
c = c - weight[i];
}
}
if (i <= number)
percent[i] = c / weight[i];//要在外面定义i,如果在for里定义int i=0,则if会报错:找不到变量i!
}
public static void main(String[] args) {
float weight[] = {5, 25, 30, 45, 50};
float value[] = {50, 200, 180, 225, 200};
int number = weight.length;
float percent[] = new float[number];//不能只float percent[],这样的数组没大小,没数组,当然默认为0.0,这样percent[i]会报错,因为for不知道percent[]的大小,它会说越界了!因为你创建数组没说明数组的大小!
for (int i = 0; i < number; i++)
percent[i] = 0;
float x[] = new float[number];
for (int i = 0; i < number; i++)
x[i] = ((value[i]) / (weight[i]));
int capacity = 100;
Bag(weight, value, capacity, number, percent);
System.out.println("背包容量为: " + capacity+" ");
System.out.println("商品数量为: "+ number);
System.out.print("商品价值为: ");
for (int i = 0; i < number; i++)
System.out.print(value[i] + " ");
System.out.println();
System.out.print("商品重量为: ");
for (int i = 0; i < number; i++)
System.out.print(weight[i] + " ");
System.out.println();
System.out.print("单位重量价值为: ");
for (int i = 0; i < number; i++)
System.out.print(x[i] + " ");
System.out.println();
System.out.print("商品百分比为: ");
for (int i = 0; i < number; i++)
System.out.print(percent[i] + " ");
System.out.println();
System.out.print("背包能装下的最大价值总和为:");
float sum = 0;
for (int i = 0; i < number; i++) {
if (percent[i] > 0)
sum = percent[i] * value[i] + sum;
}
System.out.print(sum + " ");
}
}
4、结果
5、注意事项
这里商品的重量与价值为手动排序,就是把已经排好序的数组直接写入。不另外写sort函数,(主要是写了出错就放弃了,先留坑,以后再补)