HDOJ 1009 FatMouse‘ Trade 贪心(排序)

🍑 OJ专栏


🍑 HDOJ 1009 FatMouse’ Trade
在这里插入图片描述

输入

5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1

输出

13.333
31.500

🙈 第一次看题,还以为是求 a 呢……

🍑 题意

你有 M 磅猫粮,可以在一系列仓库货比三家进行交易,求最大能获取多少豆?

🍑 思路:贪心

肯定优先挑选性价比(豆粮比)高的啦

🍑 AC

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    static int N = 1010;
    static Store[] a = new Store[N];

    static class Store implements Comparable<Store>
    {
        int j;
        int f;

        public Store(int j, int f)
        {
            super();
            this.j = j;
            this.f = f;
        }

        @Override
        public int compareTo(Store o)// 按照豆粮比排降序
        {
            return new Double((double) o.j / o.f).compareTo(new Double((double) this.j / this.f));
        }
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext())
        {
            int m = sc.nextInt();// 猫粮数量
            int n = sc.nextInt();
            if (n == -1 && m == -1)
                break;
            for (int i = 0; i < n; i++)
            {
                int j = sc.nextInt();
                int f = sc.nextInt();
                a[i] = new Store(j, f);
            }
            Arrays.sort(a, 0, n);
            double res = 0;
            for (int i = 0; i < n; i++)
            {
                int f = a[i].f;
                int j = a[i].j;
                if (m >= f)
                {
                    res += j;
                    m -= f;
                } else
                {
                    double k = (double) m / f;
                    res += j * k;
                    break;
                }
            }
            System.out.printf("%.3f", res);
            System.out.println();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值