本文主要是介绍贪心策略:FatMouse‘ Trade,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
题目描述
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehousecontaining his favorite food, JavaBean.The warehouse has N rooms. The i-th room contains Jfipounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to tradefor all theJavaBeans in the room, instead, he may get /[i]*a% pounds of JavaBeans if he pays Ffi]*a% pounds ofcat food, Here a is a real number, Now he is assigning this homework to you:tell him the maximumamount of JavaBeans he can obtain.
输入
The input consists of multiple test cases. Each test case begins with a line containing two non-negativeintegers M and N. Then N lines follow, each contains two non-negative integers J[i] and Fli]respectively, The last test case is followed by two -1's. All integers are not greater than 1000.
输出
For each test case, print in a single line a real number accurate up to 3 decimal places, which is themaximum amount of JavaBeans that FatMouse can obtain.
样例输入
5 3
7 2
4 3
5 2
20 3
25 18
24 1515 10
-1 -1
样例输出
13.333
31.500
题目大意
老鼠准备了 M 磅猫粮,并且准备拿这些猫粮和守卫仓库的猫交换自己最爱的咖啡豆(JavaBean)。仓库共有 N个房间,每个房间里面都有咖啡豆。在第i个房间内有 Ji]磅咖啡豆,但相应地需要付出 Fi磅的猫粮才能进行兑换。但是,老鼠并不一定要兑换该房间内全部的咖啡豆;相反,如果老鼠支付 a%*F[]的猫粮,那么可以获得 a%*Л[]的咖啡豆。现在请你告诉它,M磅猫粮最多可以获得多少咖啡豆。
分析
看到这一题,精于计算的读者可能会马上反应过来,这和日常买物品是一样的,每次购买商品的时候,优先挑选剩余物品中性价比(即重量价格之比)最高的物品,直到该物
品被买完或金钱耗尽。① 若当前性价比最高的物品已被买完,则继续在剩余的物品中寻找性价比最高的物品,并不断重复这个过程。
② 若当前金钱耗尽,则代表交易结束;此时,已经买到了最多的商品,输出这个最优解即可。
本题中,每个房间的咖啡豆(JavaBean)对应于不同的商品,每个房间的 J[i]代表该商品的重量,F[i]代表该商品的价格,老鼠手中的猫粮对应于金钱。
代码
import java.util.Arrays;
import java.util.Scanner;class JavaBean implements Comparable<JavaBean>{double weight;double cost;public JavaBean(double weight,double cost){this.weight = weight;this.cost = cost;}@Overridepublic int compareTo(JavaBean o) {return (int)(this.weight/this.cost - o.weight/o.cost);}
}public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while(scanner.hasNext()){//M磅猫粮int m = scanner.nextInt();//N个房间int n = scanner.nextInt();if(m == -1 && n == -1){break;}//读取数据JavaBean[] javaBeans = new JavaBean[n];for (int i = 0; i < n; i++) {double weight = scanner.nextDouble();double cost = scanner.nextDouble();JavaBean jb = new JavaBean(weight, cost);javaBeans[i] = jb;}Arrays.sort(javaBeans);float res = 0;for (int i = 0; i < n && m > 0; i++) {if(javaBeans[i].cost < m){res += javaBeans[i].weight;m -= javaBeans[i].cost;}else {res += javaBeans[i].weight * (m / javaBeans[i].cost);break;}}System.out.println(res);}}
}
这篇关于贪心策略:FatMouse‘ Trade的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!