POJ ---胖老鼠的旅行

FatMouse' Trade

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


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.
 
 
 
总结:
 
这是一道简单的贪心算法,但第一次居然WA了,想不明白错在哪里,后来看了别人的的解题报告才知道,原来有一种情况没有考虑到:
   当不需要花费代价就能得到酬劳应该最先考虑:即式子中的除数为0时    a[i].per=(a[i].j+0.0)/a[i].f;
 
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct node
{
	int j,f;     //j记录老鼠的获得量;f记录老鼠的付出量
	double per;  //per记录老鼠的单位付出所对应的获得量
}Node;
Node a[1002];
bool cmp(Node a,Node b)
{
	return a.per>b.per;
}
int main()
{
	int m,n;
	while((cin>>m>>n)&&(m!=-1)&&(n!=-1))
	{
		for(int i=1;i<=n;i++)
		{
			cin>>a[i].j>>a[i].f;
			if(a[i].f==0) a[i].per=10000000;
			else a[i].per=(a[i].j+0.0)/a[i].f;
		}
		sort(a+1,a+n+1,cmp);  //先排序,然后使用贪心;
		//for(int i=1;i<=n;i++)
			//cout<<"( "<<a[i].j<<" , "<<a[i].f<<" , "<<a[i].per<<" )"<<endl;
		double total=0;
        for(int i=1;i<=n;i++)
		{
             //if(m<=0) break;
			 if(m>=a[i].f)
			 {
				 total+=a[i].j;
				 m-=a[i].f;
			 }
			 else 
			 {
				 total+=m*a[i].per;
				 //m=0;
				 break;
			 }
		}
		printf("%.3lf\n",total);
	}
	return 0;
}

  

 
posted @ 2014-05-06 13:35  zhoudan  阅读(158)  评论(0)    收藏  举报