背包问题(不是0-1背包问题)(java实现)

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函数,(主要是写了出错就放弃了,先留坑,以后再补)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值