Java实现FatMouse‘ Trade(贪心)
问题描述如下:
Problem Description
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean. The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain. Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1s. All integers are not greater than 1000. Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain. Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.500
算法分析:
该算法采用依据兑换比例,同时将两个数组排序,然后再从头(比率最高的)进行兑换;直到兑换完为止。
参考代码:
public static void main(String[] args) { // TODO Auto-generated method stub int m, n, i, j, tempa, tempb; float temp; float sum = 0; Scanner scanner = new Scanner(System.in); System.out.println("请输入有多少猫粮:"); m = scanner.nextInt(); System.out.println("请输入有多少房间:"); n = scanner.nextInt(); System.out.println("猫粮:" + m + " 房间:" + n); int a[] = new int[n]; int b[] = new int[n]; float r[] = new float[n]; System.out.println("依次输入可兑换的javabean,和需要的猫粮:"); for (i = 0; i < n; i++) { a[i] = scanner.nextInt(); b[i] = scanner.nextInt(); r[i] = (float) a[i] / b[i]; } for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) if (r[j] < r[j + 1]) { temp = r[j]; r[j] = r[j + 1]; r[j + 1] = temp; tempa = a[j]; a[j] = a[j + 1]; a[j + 1] = tempa; tempb = b[j]; b[j] = b[j + 1]; b[j + 1] = tempb; } } if (m > 0) { for (i = 0; i < b.length; i++) { if (m >= b[i]) { sum += a[i]; m = m - b[i]; } else { sum += (float) m / b[i] * a[i]; break; } } } else { System.out.println("兑换结束!!!!"); } System.out.println(sum); }