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
Author: CHEN, Yue
Source: Zhejiang Provincial Programming Contest 2004
分析:
题意:
给定若干数据,每个数据包含两个值,一个是a,一个是b,性价比是a/b。要求每次取性价比高的,且b的和不能超过给定的m。输出a的和的最大值。
简单题。可分割的背包问题,贪心策略,不需用到dp就能解决。
重点练习结构体排序,终于搞懂了结构体排序的原理。么么哒。
ac代码:
#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxm=1000;
const int maxn=1000;
struct Mouse
{
double a,b;
bool operator <(const Mouse &m2) const//运算符重载,注意没有>运算符重载,要表示大于关系,只需改变重载函数下面的符号
{
//return m2.a/m2.b<a/b;//由大到小排序,用<;由小到大排序,用>
return a/b>m2.a/m2.b;//由大到小排序,用>;由小到大排序,用<。这种表示法更直观
}
}mouse[maxm];
int main()
{
int n,i,j;
double m;
while(scanf("%lf%d",&m,&n)&&m!=-1&&n!=-1)
{
for(i=0;i<n;i++)
scanf("%lf%lf",&mouse[i].a,&mouse[i].b);
sort(mouse,mouse+n);
//for(i=0;i<n;i++)
//cout<<mouse[i].a<<" "<<mouse[i].b<<" "<<mouse[i].a/mouse[i].b<<" "<<endl;//测试
double s=0;
for(i=0;i<n&&m>0;i++)
{
if(m>=mouse[i].b)
{
s+=mouse[i].a;
m-=mouse[i].b;
}
else if(m<mouse[i].b)
{
s+=mouse[i].a*m/mouse[i].b;
m=0;
}
}
printf("%.3lf\n",s);
}
return 0;
}