hdu-1009 FatMouse' Trade 贪心算法

来源:互联网 发布:淘宝店铺内衣名字大全 编辑:程序博客网 时间:2024/05/22 03:22


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磅猫粮,准备与守卫仓库的猫交换它最喜欢的食物。第一行输入两个整数m和n,表示老鼠有m磅猫粮,猫的仓库有n个房间,接下来是n组数据,每组数据包括两个整数老鼠和猫交换的粮食数量,如第一组老鼠可以用2磅猫粮交换7磅粮食。计算出老鼠可以得到的最多粮食磅数。

毫无疑问的贪心算法,既然老鼠要得到最多磅数的粮食,则老鼠必须用最少的猫粮换最多的粮食。
现将每组数据排序,按每磅猫粮可以交换的粮食从多到少排序。如第一组测试数据,第一组数据中每磅猫粮可以叫唤3.5磅粮食,第二组中每磅猫粮可以交换1.333磅粮食,第三组中每磅猫粮可以交换2.5磅粮食,排序后的数组为7 2,5 2,4 3,老鼠的五磅猫粮前四磅交换了7+5=12磅粮食,最后一磅交换了最后一组中4的1/3磅粮食,所以老鼠交换的总粮食磅数为13.333磅粮食。

ps.这里可以优化的是,如果老鼠的猫粮总量大于所有房间内猫粮总量之和,说明老鼠可以拿到所有的粮食,直接输出粮食之和即可。

AC代码
#include <stdio.h>#include <string.h>double a[1010][2];int main(){    double temp;    int i,m,n,k;    double sum1,sum;    while (scanf("%d %d",&m,&n)!=EOF) {        sum=0;sum1=0;        memset(a, 0, sizeof(a));        if(m==-1&&n==-1)            return 0;        for(i=0;i<n;i++){            scanf("%lf %lf",&a[i][0],&a[i][1]);            sum=sum+a[i][1];            sum1=sum1+a[i][0];        }        if(m>=sum){            printf("%.3lf\n",sum1);            continue;        }        sum=0;sum1=0;        for(i=0;i<n;i++)            for(k=i+1;k<n;k++)                if(a[k][0]/a[k][1]>a[i][0]/a[i][1])                {                    temp=a[k][0];                    a[k][0]=a[i][0];                    a[i][0]=temp;                    temp=a[k][1];                    a[k][1]=a[i][1];                    a[i][1]=temp;                }        for(i=0;i<n;i++){            sum=sum+a[i][1];            if(sum>m){                sum=sum-a[i][1];                break;            }            sum1=sum1+a[i][0];        }        printf("%.3lf\n",sum1+1.0*a[i][0]*(m-sum)/a[i][1]);    }}

原创粉丝点击