老鼠和猫换食物题:(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;}
- 老鼠和猫换食物题:(Problem ID:1009)
- Problem 1019 猫捉老鼠
- fuzhuo-----Problem 1019 猫捉老鼠
- FZU Problem 1019 猫捉老鼠
- HDOJ 1009 FatMouse' Trade (胖老鼠和猫做生意,贪心)
- HDU 电梯题:(Problem ID:1008)
- 数学归纳法题:(Problem ID:1098)
- 不超过地下通道题(Problem ID:1037)
- 最小公倍数题(Problem ID:1108)
- 猜数字题(Problem ID:1172)
- 换ID
- 猫抓老鼠 floyd SRM 670 Div2 Problem 1050 - Treestrat
- 【贪心】老鼠和猫的交易
- HDU 算术不同解法题:(Problem ID:1028)
- 骨头陷阱,小狗过迷宫题(Problem ID:1010)
- Edge水流向题(Problem ID:1033)
- 水上升下降抵消题(Problem ID:1049)
- 猴子放箱子吃香蕉题(Problem ID:1069)
- jQuery效果之选项卡三
- Stereo Matching文献笔记之(九):经典算法Semi-Global Matching(SGM)之神奇的HMI代价计算~
- 数学归纳法题:(Problem ID:1098)
- jQuery效果之滑动面板
- 进制介绍与进制之间的转换
- 老鼠和猫换食物题:(Problem ID:1009)
- 工作中不要总是问什么是什么!
- Qt中使用到的设计模式之反射模式
- Python常用方法(一)
- leetcode-49 Group Anagrams 同位词字典序排序
- Maven是什么
- Boost库的字符串处理算法
- ASP.NET 开发中弹出提示对话框的2种方法
- C++正则表达式库