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.
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
Sample Output
13.333 31.500
首先根据题意我们可以求出f[i]/j[i]的值,类似性价比,然后根据又大到小排序,然后在m的范围内依次与猫交换,直到不能完整的把一个房间里的咖啡豆全部交换,停止交易。此题的模型为部分背包问题,即可以取一个房间内一部分,而不用全部取。这题感觉很容易WA,本屌就WA了五次,其中脑袋秀逗的一下,明明可以直接加上一个房间可以获得的咖啡豆,还偏偏手残要取个平均值再乘以给的猫粮,下面贴下本题AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1010;
struct rate //据discuss说float型过不去,我要开始就是用double,所以没测试过
{
double temp;
double get;
double pay;
} a[maxn];
bool cmp(struct rate a,struct rate b) //此处结构体数组的排序,可以好好的看下
{
return a.temp > b.temp;
}
int main()
{
double m;
int n;
int i;
double sum;
while(cin>>m>>n && m != -1 && n != -1)
{
sum = 0.0;
for(i=1; i<=n; i++)
{
cin>>a[i].get>>a[i].pay;
a[i].temp = a[i].get / a[i].pay;
//cout<<a[i].temp<<endl;
}
sort(a+1,a+n+1,cmp);
/*for(i=1;i<=n;i++)
{
cout<<"排序后为:"<<a[i].temp<<" ";
cout<<"::"<<a[i].get<<" ";
cout<<"::"<<a[i].pay<<" ";
}
cout<<endl; */
for(i=1; i<=n; i++)
{
if(m - a[i].pay >0)
{
sum += a[i].get; //此处便是手残了一下写成:sum += a[i].temp * a[i].pay,就WA了;
m -= a[i].pay;
}
else
{
sum += a[i].temp * m;
m = 0;
break;
}
}
printf("%.3lf\n",sum);
}
}

本文探讨了一道经典的计算机科学问题——肥鼠利用有限数量的猫粮换取尽可能多的咖啡豆。通过分析不同房间中咖啡豆与猫粮的交换比率,采用排序与贪心策略求解最大收益。
991

被折叠的 条评论
为什么被折叠?



