hdu 1009 FatMouse' Trade(贪心)

来源:互联网 发布:大数据分析师待遇 编辑:程序博客网 时间:2024/05/20 02:22

FatMouse' Trade

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


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 37 24 35 220 325 1824 1515 10-1 -1
 

Sample Output
13.33331.500

题意:手上有m克猫粮,有n个房间,每个房间有一只猫,每只猫的需求不同,给第i只猫猫f[i]克猫粮可以获得价值为就j[i]的东西,猫粮可以只给一部分,然后猫也给你一部分价值的东西,问你最多可以得到多少价值?

思路:猫粮可以只给一部分,明显的贪心,如果必须完全给,那就是01背包问题。

按照价值/猫粮重量从大到小排序,一直取到猫粮用完就OK。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;#define N 1010struct Room{    double j,f;}room[N];bool cmp(Room a,Room b){    return (a.j/a.f)>(b.j/b.f);}int main(){    int n,m;    while(~scanf("%d %d",&m,&n)&&m!=-1)    {        for(int i=0;i<n;i++)                scanf("%lf %lf",&room[i].j,&room[i].f);        sort(room,room+n,cmp);        double ans=0;        for(int i=0;i<n;i++)        {            if(m>room[i].f)            {                m-=room[i].f;                ans+=room[i].j;            }            else            {                ans+=room[i].j*(m/room[i].f);                break;            }        }        printf("%.3lf\n",ans);    }    return 0;}


0 0