题目描述
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 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.
输出
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.
样例输入
4 2 4 7 1 3 5 5 4 8 3 8 1 2 2 5 2 4 -1 -1
样例输出
2.286 2.500
//本题用贪心算法:
这也是一个部分背包问题,贪心算法是一个自顶而下的算法,通过贪心选择来构造一个子结构,以产生一个待优化解决的子问题。
//部分背包问题,对于一种物品,可以选择拿(包括拿一部分)或不拿,但这个拿一般都会尽量贪心的拿最多,本题FatMouse如何交换最多的JavaBeane呢?
首先要计算出对于每个仓库中,一个单位的猫粮可以换多少JavaBeane,然后从大到小进行排序,之后FatMouse就可以拿猫粮来换了,哈哈,而且按顺序换每一次都可以换最多~~
注意:要考虑当仓库规定可以用0猫粮换JavaBeane的情况!
代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
struct Node
{
int j;//JavaBeane
int f; //猫粮
double percent;//一个单位的猫粮可以换得的JavaBeane
} Q[3001];
bool cmp(Node a,Node b)
{
return a.percent>b.percent;//从大到小排序
}
int main()
{
int n,m;//m磅猫粮,n个格子
while(~scanf("%d%d",&m,&n))
{
if(n==-1||m==-1) break;
int i;
for(i=0;i<n;i++)
{//第i格子中,j食物由f猫粮换得
scanf("%d%d",&Q[i].j,&Q[i].f);
Q[i].percent=(double)Q[i].j/Q[i].f;//性价比
}
sort(Q,Q+n,cmp);//排序:从大到小
double sum=0;//表示老鼠吃到的总食物数
for(i=0;i<n;i++)
{
if(m>Q[i].f)
{ //如果剩下的猫粮还大于换取某个仓库JB所需猫粮,则把仓库里面的JB全部换走
sum+=Q[i].j;
m-=Q[i].f;
}
else //最后剩下的猫粮换不了某个仓库里面的全部JB,则换取部分即可,并且结束了交易
{
sum+=Q[i].percent*m;
m=0;
break;
}
}
printf("%.3lf\n",sum);
}
return 0;
}