HDU 1009 贪心算法之FatMouse

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个房间,每个房间前有一只猫,房间里有老鼠最喜欢的食品JavaBean,J[i]。若要引开猫,必须付出相应的猫食F[i]。当然这只老鼠没必要每次都付出所有的F[i]。若它付出F[i]的a%,则得到J[i]的a%。求老鼠能吃到的做多的JavaBean。

思路:老鼠要吃到最多的食物,则每次花费需要付出最少的猫粮,因此,单位猫粮换取的食物越多,最终能吃到的最多。于是便将求解一个问题的最优解分成求解若干个子问题的最优解。因此,算出J[i]/F[i],再从大到小排序,每次在不超过剩余猫粮的情况下获取该房间的所有食物,若猫粮不足以换取该房间的所有食物,则再加入剩余猫粮在这个房间所能换取的最多食物,求和即为最终结果。

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
struct node              
{
	double J,F;
	double prop;//比例
}a[1005];
int cmp(node a,node b)
{
	return a.prop>b.prop;             //结构体数组按性价比从大到小排序
}
int main()
{
	double m;
	int n;
	while(~scanf("%lf%d",&m,&n))
	{
		if(m==-1&&n==-1)break;
		for(int i=0;i<n;i++)
		{
			scanf("%lf %lf",&a[i].J,&a[i].F);
			a[i].prop=a[i].J/a[i].F;
		}
		sort(a,a+n,cmp);
		double sum=0;
		for(int i=0;i<n;i++)
		{
			if(m>a[i].F)                  
			{
				sum+=a[i].J;
				m-=a[i].F;
			}
			else
			{
				sum+=a[i].J*(m/a[i].F);
				break;
			}
		}
		printf("%.3lf\n",sum);     //注意输出精度为3位小数
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43965640/article/details/88044446