HDU 1009 FatMouse' Trade 详解

来源:互联网 发布:股票买卖软件 编辑:程序博客网 时间:2024/06/01 23:38

FatMouse' Trade


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 Jii pounds of JavaBeans and requires Fii pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get Jii* a% pounds of JavaBeans if he pays Fii* 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 Jii and Fii 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个房间,每个房间都有一只小猫咪守着,小老鼠共有n个可付出的代价,在某个房间,小老鼠可以以一定比例付出代价获得相应的收获,所以该题是要求解小老鼠可以获得的最大的收获。
具体分析:由于每个房间都包含了小老鼠需要付出的代价、小老鼠最多可以获得的收获和该房间的比例三个元素,所以在此采用结构体的构造。接下来的求解就比较容易了,当我们输入每个房间的代价和收获后,分别计算每个房间的比例(收获/代价),并把每个房间的比例按从大到小的顺序排列(这一步的意义:小老鼠最终要获得最大的收获,达到的方法是用最少的代价获得最多的收获,而房间比例大时,相应的可以达到这种效果),然后从比例最大的房间开始获得收获,如果最后的代价不足以获得这个房间内的所有收获,这是按比例获得代价相应的收获。

附上AC代码:

#include<stdio.h>#include<iostream>#include<algorithm>using namespace std;struct Tode{int shouhuo,daijia;double percent;}mouse[1005];int ss(Tode a,Tode b){return a.percent>b.percent;}int main(){int m,n,i,j;while(cin>>n>>m&&(n!=-1||m!=-1)){for(i=0;i<m;i++){cin>>mouse[i].shouhuo>>mouse[i].daijia;mouse[i].percent=(double)mouse[i].shouhuo/mouse[i].daijia;}sort(mouse,mouse+m,ss);double sum=0;for(i=0;i<m;i++){if(n>mouse[i].daijia){sum+=mouse[i].shouhuo;n-=mouse[i].daijia;}else{sum+=n*mouse[i].percent;n=0;break;}}printf("%.3lf\n",sum);}return 0;}


原创粉丝点击