FatMouse' Trade HDU - 1009 ( 贪心 )

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SEVENY_/article/details/83114727

FatMouse' Trade 

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

题意:

n为现在手中的猫粮数,m为可以交易的房间数。每个房间中有j个食物和f个猫粮,用f个猫粮可以换到j个食物,要求用n个猫粮来换到最多的食物。

所以需要先排序,1个猫粮换到最多的食物优先。先换j/f比值最大的。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct Node{
	double j,f;  //食物,猫粮 
	double price;  //食物与猫粮的比值 
};
struct Node node[100007];
 //要优先选择食物/猫粮大的值,说明1份猫粮换到的食物更多 
int cmp(struct Node a,struct Node b)
{
	return a.price>b.price;
}
int main()
{
	int m,n;
	while(scanf("%d%d",&n,&m)!=EOF&&m!=-1&&n!=-1)
	{
		double sum=0;
		for(int i=0;i<m;i++)
		{
			scanf("%lf%lf",&node[i].j,&node[i].f);
			node[i].price=node[i].j/node[i].f;   //比值
		} 
		sort(node,node+m,cmp);  //排序
		for(int i=0;i<m;i++)
		{
			if(n>node[i].f)  //如果猫粮比房间中的猫粮多
			{
				sum+=node[i].j;  //那么可以换到全部的食物
				n-=node[i].f;
			}
			else  //如果手中的猫粮少于房间的猫粮时
			{
				sum+=node[i].price*n;
				break; 
			} 
		}
		printf("%.3lf\n",sum);
	}
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/SEVENY_/article/details/83114727