首页 > 代码库 > hdu1009

hdu1009

 

                                                      FatMouse‘ Trade

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4555 Accepted Submission(s): 1354
 
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
 

刚开始用了一个比较普通的算法:1循环输入数据,2根据“好坏”排序数据,3得到最优解;验证数据正确,可能是这个算法太繁琐导致超时,遗憾不能ac

 

 1 #include<stdio.h> 2 int main() 3 { 4     int m,n,i,s; 5     double j[1005],f[1005],t[1005],tmpt,tmpj,tmpf,cha,max=0; 6     while(scanf("%d%d",&m,&n)!=EOF) 7     { 8         if(m<=0&&n<=0) 9             break;10         max=0;11         for(i=0;i<n;i++){12             scanf("%lf%lf",&j[i],&f[i]);13             t[i]=j[i]/f[i];14         }15         for(i=0;i<n-1;i++)16             for(s=1;s<n;s++)17                 if(t[i]<t[s])18                     {19                         tmpt=t[i];  tmpj=j[i];    tmpf=f[i];20                         t[i]=t[s];    j[i]=j[s];    f[i]=f[s];21                         t[s]=tmpt;    j[s]=tmpj;    f[s]=tmpf;22                     }23         24         i=0;25         while(m)26         {27             if(m>=f[i]){28             max +=j[i];29             m -=f[i];30             i++;31             }32             else{33             cha=m/f[i];34             max +=j[i]*cha;35             m=0;36                 i++;37             }38             if(i>=n)39                 break;40         }41         printf("%.3f\n",max);42         i=0;max=0;43         44     }45     return 0;46 }