题目:
FatMouse' Trade |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 5092 Accepted Submission(s): 1530 |
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 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1 |
Sample Output 13.333 31.500 |
Author CHEN, Yue |
Source ZJCPC2004 |
Recommend JGShining |
题目大意:
老鼠准备了M磅猫食,准备拿这些猫食跟猫交换自己喜欢的食物。有N个房间,每个房间里面都有食物。你可以得到J[i]但你需要付出F[i]的猫食。要你计算你有M磅猫食可以获得最多食物的重量。而且这里可以不必每一组都全换,可以按比例换。。。例如最后你只剩5块钱猫食。但是目前的一个选择是话10块猫食就能换取6个粮食。那么这时候你用5块猫食就能换取3个粮食
题目分析:
这是一道简单的贪心题。对于这种获得收入的同时需要付出一些的情况下,计算最大收入。这种题一般是根据
收入和付出的比例来排一下序。然后根据这个比例从高到低进行选择
代码如下:
/*
* a.cpp
*
* Created on: 2015年1月28日
* Author: Administrator
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 10005;
struct W {
double get;//收入
double pay;//付出的猫食
double ave;//收入/付出比
} w[maxn];
bool cmp(W a, W b) {
if (a.ave > b.ave) {
return true;
}
return false;
}
int main() {
int n;
double m;
while (scanf("%lf%d", &m, &n), n != -1 && m != -1) {
int i;
for (i = 0; i < n; ++i) {
scanf("%lf %lf", &w[i].get, &w[i].pay);
w[i].ave = w[i].get / w[i].pay;
}
sort(w, w + n, cmp);//贪心,对w按照get/pay进行降序排序
double sum = 0;
i = 0;
// while(m >= 0){//不知道为什么这种写法就是不行.
// if (m >= w[i].pay) {
// sum = sum + w[i].get;
// m = m - w[i].pay;
// } else {
// sum = sum + w[i].ave * m;
// break;
// }
// i++;
// }
for (i = 0; i <= n - 1; i++) {
if (m >= w[i].pay) {//如果当前剩余的猫食还足够的话
sum = sum + w[i].get;//那就把那个房间的粮食全部买下
m = m - w[i].pay;//并且手上见去相应的猫食
} else {//如果现在手上的猫食已经不够
sum = sum + w[i].ave * m;//那么就按比例拿去一定的猫食
break;
}
}
printf("%.3lf\n", sum);
}
return 0;
}