🍑 OJ专栏
输入
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();
}
}
}