HDOJ 1009 FatMouse’ Trad
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
题意:肥老鼠准备了M磅的猫粮,准备和看守他最喜欢的食物爪哇豆仓库的猫交易。
这个仓库有N个房间。第i个房间有J[i]磅的爪哇豆,需要F[i]磅的猫粮。胖鼠不需要用房间里所有的爪哇豆来交换,相反,如果他支付F[i]*a%磅的猫粮,他可以得到J[i]*a%磅的爪哇豆。这是一个实数。现在他给你布置了一个家庭作业:告诉他他能获得的javabean的最大数量。
贪心算法题,首先计算一磅猫粮与Javabean的比例然后按照比例从高到底排序,我们优先兑换比例大的房间里的Javabean,这样我们可以把老鼠得到的豆子数值最大化。
#include<iostream>
#include<algorithm>
using namespace std;
struct Room_food
{
int j;
int f;
double scale;
};
bool cmp(Room_food x, Room_food y); //排序条件
Room_food rf[3001];
int main(void)
{
int m, n;
int i;
while (cin >> m >> n && (m != -1 || n != -1))
{
for (i = 0; i < n; i++)
{
cin >> rf[i].j >> rf[i].f;
//计算存储一磅猫粮与Javabean的比例
rf[i].scale = (double)rf[i].j / rf[i].f;
}
sort(rf, rf + n, cmp);
double java_bean = 0;
//从0开始也就是从高比例开始,比例越高能换的总数越多
for (i = 0; i < n; i++)
if (rf[i].f > m)
{
java_bean += rf[i].scale * m;
//把全部猫粮换完了
m = 0;
break;
}
else
{
//减去已经换完的猫粮
m -= rf[i].f;
java_bean += rf[i].j;
}
printf("%.3f\n", java_bean);
}
return 0;
}
bool cmp(Room_food x,Room_food y)
{
//按照比例从高到低排序
return x.scale > y.scale;
}