部分背包问题-贪心算法(java实现)

在这里插入图片描述

public class franctionalKnapsack {
    public static class Goods{
        String name;
        int weight;
        int value;
        float valuePerWeight;
        //每一个物品都拥有质量和体积等属性,为了方便调用写一个构造器
        public Goods(String name, int weight, int value) {
            this.name = name;
            if (weight>0){
                this.weight = weight;
                this.valuePerWeight= (float)value / (float)weight;//强制转换数据类型
            }
            this.value = value;
        }
    }

    public static void main(String[] args){
        //这里用的只是一维数组
        Goods[] input = new Goods[5];
        //每一个input中存放的是上面的构造器
        input[0] = new Goods("苏打水",600, 60);
        input[1] = new Goods("汽水",250,10);
        input[2] = new Goods("橙汁",200,36);
        input[3] = new Goods("苹果汁",100,16);
        input[4] = new Goods("西瓜汁",300, 45);
        int result = franctionalKnapsack(input, 800, 5);
        System.out.print("最大价值:"+result);
    }

    //传入物品的属性,按性价比进行递归排序
    private static void quickSortSimple(Goods[] A, int l, int r){
        Goods temp;
        int i=l;
        int j=r;
        if(l<r){
            temp = A[i];
            while(i!=j){
                while(i<j && A[j].valuePerWeight <= temp.valuePerWeight){
                    j--;
                }
                A[i] = A[j];
                while(i<j && A[i].valuePerWeight >= temp.valuePerWeight){
                    i++;
                }
                A[j] = A[i];
            }
            A[i] = temp;
            quickSortSimple(A, l, i-1);
            quickSortSimple(A, i+1,r);
        }
    }

    //贪心算法核心
    private static int franctionalKnapsack(Goods[] goods, int C, int n){
        //传入物品的属性,进行排序
        quickSortSimple(goods, 0, goods.length-1);
        int i = 0;
        int ans = 0;
        //背包还有空间,还有商品
        while(C>0 && i<n){
            if(goods[i].weight<=C){
                System.out.println("选择商品"+goods[i].name);
                ans += goods[i].value;
                C -= goods[i].weight;
            }else{
                System.out.println("选择"+C+"体积的商品"+goods[i].name);
                ans += C * goods[i].valuePerWeight;
                C = 0;
            }
            i++;
        }
        return ans;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值