背包问题——分数背包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wdays83892469/article/details/79765419

贪心问题

分数背包

分数背包与01背包问题不同点就是如果某物品无法被全部放入可以放入一部分
思路还是降序排列然后往背包添加

题目:
有 m 元钱,n 种物品;每种物品有 j 磅,总价值 f 元,
可以使用 0 到 f 的任意价格购买相应磅的物品,例如使用 0.3f 元,
可以购买 0.3j 磅物品。要求输出用 m 元钱最多能买到多少磅物品。
输入样例
3 5 //物品数量n 背包承重
7 2 //价值 重量
4 3
5 2

/* 分数背包问题
 * 
 */
public class 分数背包 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int n=input.nextInt();
        double m=input.nextDouble();
        Good goods[]=new Good[n]; 
        for (int i = 0; i < n; i++) {
            goods[i]=new Good();
            goods[i].j=input.nextDouble();
            goods[i].f=input.nextDouble();
            goods[i].s=goods[i].j/goods[i].f;//计算性价比
        }
        Cmp cmp=new Cmp();
        Arrays.sort(goods,cmp);// 使各物品按照性价比降序排列
        int index=0;//当前货物下标 
        double ans=0;//累加所能得到的总重量 
        while(m>0&&index<n) {//循环条件为,既有物品剩余(index<n)还有钱剩余(m>0)时继续循环 
            if(m>goods[index].f) {//若能买下全部该物品 
                ans+=goods[index].j;
                m-=goods[index].f;
            }else{//若只能买下部分该物品 
                ans+=goods[index].j*m/goods[index].f;
                m=0;
            } 
            index++;//继续下一个物品 
        }
        System.out.printf("%.3f\n",ans);
        }

}
class Cmp implements Comparator<Good>{
    @Override
    public int compare(Good g1, Good g2) {
        return (int)(g2.s-g1.s);
    }   
}
class Good {
    double j;// 该物品总重
    double f;// 该物品总价值
    double s;// 该物品性价比
}

猜你喜欢

转载自blog.csdn.net/wdays83892469/article/details/79765419