老鼠和猫换食物题:(Problem ID:1009)

来源:互联网 发布:linux配置vnc centos 编辑:程序博客网 时间:2024/05/16 08:37

题址:http://acm.hdu.edu.cn/showproblem.php?pid=1009


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磅猫食,准备和猫换它最喜欢的JavaBean,房子有N个房间,第i个房间有J[i]磅JavaBean并且允许换F[j]磅猫食。老鼠可以不换掉房间里全部的JavaBean,它可以用F[j]*a%猫食换J[i]*a%的JavaBean,题目意思大概就是这样了。


题目思路:贪心算法解决。先求比重a[i]=(double)j[i]/f[i],再做排序就可以了。注意,因为老鼠可以不换掉全部的,那么就要计算最后一次换的时候换的量,由百分比计算m*a[i]即(double)m*j[i]/f[i]去计算。主要点就是这些了,具体实现参见下面AC代码。奋斗


AC代码:

#include<stdio.h>#define M 1000int main(){int m,n,i,k,j[M],f[M],t1,t2;double a[M],temp,sum;while(scanf("%d%d",&m,&n)&&(m!=-1||n!=-1)){i=0;k=n;sum=0;while(k--){scanf("%d%d",&j[i],&f[i]);a[i]=(double)j[i]/f[i];i++;}for(i=0;i<n-1;i++){for(k=0;k<n-1-i;k++){if(a[k]<a[k+1]){temp=a[k],a[k]=a[k+1],a[k+1]=temp;t1=j[k],j[k]=j[k+1],j[k+1]=t1;t2=f[k],f[k]=f[k+1],f[k+1]=t2;}}}for(i=0;i<n;i++){if(m>f[i]){sum+=j[i];m=m-f[i];}else{sum+=(double)m*j[i]/f[i];break;}}printf("%.3lf\n",sum);}return 0;}

1 0
原创粉丝点击