题目:
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
一个被自己蠢到笑死的题。。。很正常的想到了性价比,也想到了0 1和1 0 0 1的特殊情况,猫粮剩下的情况,然后光荣的wa。。。一大早起来看,原来是觉得没什么关系的循环中的判断段顺序造成的。
下面是过了的代码:
#include<iostream>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<set>
using namespace std;
struct foo
{
double a, b;
double ave;
}f[1005];
bool cmp(foo c,foo d)
{
return c.ave>d.ave;
}
int main()
{
double m;
int n;
while(cin>>m>>n)
{
if(m<0&&n<0) break;
else
{
for(int i=0;i<n;i++)
{
cin>>f[i].a>>f[i].b;
f[i].ave=f[i].a/f[i].b*1.0;//
}
sort(f,f+n,cmp);
double ans=0;
int i=0;
while(m>=0)
{
if(i==n) break;
if(m<=f[i].b)
{
ans+=m*f[i].ave;
break;
}
else if(m>f[i].b)
{
m-=f[i].b;
ans+=f[i].a;
i++;
}
}
printf("%.3lf\n",ans);
}
}
return 0;
}
wa的代码:
#include<iostream>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<set>
using namespace std;
struct foo
{
double a, b;
}f[1005];
bool cmp(foo c,foo d)
{
return c.a/c.b>d.a/d.b;//最好两个数直接比较吧
}
int main()
{
double m;
int n;
while(cin>>m>>n)
{
if(m<0&&n<0) break;
if(n==0||m==0) //首先是这里,没房间没猫粮,哪会有豆子可换,直接就输出0,但是两个问题,1.没猫粮有房间,说明还有输入,2.真有不需要猫粮也可以换豆子的房间的话,n/0=INF,和0没关系啊。真的蠢到了,而且事实证明,并不需要单独拎出来这两种情况。
{
int u=0;
cout<<u;
continue;
}
else
{
for(int i=0;i<n;i++)
{
cin>>f[i].a>>f[i].b;
}
sort(f,f+n,cmp);
double ans=0;
int i=0;
while(m>0)//一定要先判断是否m<=f[i].b,一个例子是0 1 1 0
{
if(i==n) break;
if(m>=f[i].b)
{
m-=f[i].b;
ans+=f[i].a;
i++;
}
else if(m<f[i].b)
{
ans+=m*f[i].a/f[i].b;
i++;
}
}
printf("%.3lf\n",ans);
}
}
return 0;
}