贪心算法-背包物品可切割

可分割背包问题很容易理解,只需要根据收益和重量的比值进行排序,首选比值较大者填入即可,若物品种类大于剩余载重量,则填充剩余载重量的此物品,在剩余载重量足够的情况下,依次将物品填入背包即可。 

import java.util.*;
public class Beibao {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        int num=Integer.parseInt(in.nextLine());
        List b=new ArrayList<B>();
        for(int i=0;i<num;i++){
            String str=in.nextLine();
            String s[]=str.split(" ");
            b.add(new B(s[0].charAt(0),Double.parseDouble(s[1]),Double.parseDouble(s[2])));
        }
        for(int i=0;i<num;i++){
            B temp=(B)b.get(i);
            System.out.println(temp.ch+" "+temp.weight+" "+temp.value);
        }
        System.out.println();
        Collections.sort(b, new Comparator<B>() {
            @Override
            public int compare(B o1, B o2) {
                if(o1.bi-o2.bi>0){
                    return -1;
                }else{
                    return 1;
                }
            }
        });
        for(int i=0;i<num;i++){
            B temp=(B)b.get(i);
            System.out.println(temp.ch+" "+temp.weight+" "+temp.value+" "+temp.bi);
        }
        int M=Integer.parseInt(in.nextLine());
        double money=0;
        for(int i=0;i<num && M>0;i++){
            B temp=(B)b.get(i);
            if(M-temp.weight>=0){
                money+=temp.value;
                M-=temp.weight;
            }else{
                money+=M*temp.bi;
                M=0;
            }
        }
        System.out.println(money);
    }
}
class B{
    char ch;
    double weight;
    double value;
    double bi;
    B(char ch1,double weight1,double value1){
        ch=ch1;
        weight=weight1;
        value=value1;
        bi=value/weight1;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值