HDOJ1019 FatMouse' Trade(贪心)

来源:互联网 发布:水晶古筝知乎 编辑:程序博客网 时间:2024/06/06 01:00

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 84040    Accepted Submission(s): 29105


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 -1's. 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 37 24 35 220 325 1824 1515 10-1 -1
 

Sample Output
13.33331.500
 
题意:FatMouse拿着猫粮去和猫做生意。
FatMouse带了M的猫粮,猫使用JavaBean和FatMouse交换。
猫的仓库有N个房间,每个房间有J[i] 的JavaBean。老鼠需要使用F[i]的猫粮才能全部交换过来。
但是他不是每个仓库都100%的交换,而是交换a%。
这个a%就是关键了,我们先将J[i]/F[i],排序,得到交易利润的序列。
然后从利润的高到低进行交换。当不能100%的交换时,就算出能交换百分之多少。
下面AC代码:
import java.util.Scanner;public class Main{private static Scanner scanner;private static int[] J;private static int[] F;private static double[] value;public static void main(String[] args) {scanner = new Scanner(System.in);while (scanner.hasNext()) {int m = scanner.nextInt();// 老鼠带的猫粮int n = scanner.nextInt();// n行数据if (m == -1 && n == -1) {break;}J = new int[n];F = new int[n];value = new double[n];// 收益比例(相当于背包问题的价值)for (int i = 0; i < n; i++) {J[i] = scanner.nextInt();F[i] = scanner.nextInt();value[i] = 1.0 * J[i] / F[i];}sort();// 排序double sum = 0;for (int i = 0; i < n; i++) {if (F[i] < m) {sum += J[i];m -= F[i];} else {sum += 1.0*m/F[i]*J[i];break;}}System.out.printf("%.3f",sum);System.out.println();}}// 按照value高到低排序private static void sort() {for (int i = 0; i < F.length - 1; i++) {for (int j = i + 1; j < F.length; j++) {if (value[i] < value[j]) {double dt = value[i];value[i] = value[j];value[j] = dt;int it = J[i];J[i] = J[j];J[j] = it;it = F[i];F[i] = F[j];F[j] = it;}}}}}




原创粉丝点击