首页 > 代码库 > HDU 1009 贪心问题
HDU 1009 贪心问题
FatMouse‘ Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 46205 Accepted Submission(s): 15482
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.
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
Author
CHEN, Yue
Source
ZJCPC2004
这道题是道贪心的题目,就是题目有点难懂,很早之前就想做这题了,奈何题目一直看不懂,花了很大功夫理解了题目。然后今天终于做出来了。。题意:老鼠有m克的猫粮,想去跟猫兑换食物,但是老鼠喜欢的食物在仓库的不同层,每层的兑换率都不一样。求的是最多能兑换到多少食物。
5 3
7 2
4 3
5 2
这个案例代表有老鼠有5克猫粮 ,食物一共放在不同的三层 ,第一层有7克食物,需要2克猫粮兑换,兑换率为7/2;第二层第三层类似。
所以要贪心的话,就要先选出兑换率最大的一层开始兑换。上代码上解析。
#include <stdio.h> #define wbx 50000 int a[wbx]; //wbx代表第wbx层,a[wbx]代表第wbx层的食物。 int b[wbx]; //b[wbx]第wbx层的猫粮。 double p[wbx];// p代表第wbx层的兑换率。 #include <string.h> #include <algorithm> using namespace std; void solve() { int m,n; while(scanf("%d%d",&m,&n)&&m!=-1 &&n!=1) { int i,k; double sum=0; for(i=1;i<=n;i++) { scanf("%d%d",&a[i],&b[i]);//输入每层的食物和猫粮 p[i]=double(a[i]*1.0/b[i]); //算出每层的兑换率 } while(m!=0 &&n!=0) //m=0或者n=0代表着结束,跳出循环。 { double max=-999; for(i=1;i<=n;i++) { if(p[i]>max) { max=p[i];//每次都先找出每层兑换率最大的。 k=i;//把值赋给k。 } } if(m-b[k]>=0)// 如果猫粮大于等于这层的猫粮 { m-=b[k];// 减去这层的猫粮。 sum+=a[k];// 得到这层所有食物。 p[k]=0;// 这层兑换完了,让它的兑换率为0。 } else { sum+=m*p[k];// 如果剩余猫粮已经小于想兑换的这层的猫粮,那就用剩下的猫粮兑换所有的食物。 m=0;//猫粮为0,跳出循环。 } } sum=double(sum); printf("%.3lf\n",sum);//sum就是最优解。。 } } int main() { solve();//问题解决。。 return 0; }
HDU 1009 贪心问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。