hdu 1009 FatMouse' Trade(贪心)

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

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
题目的大致意思为:肥鼠用猫粮(cat food)换咖啡豆(javabeans),已知它有m磅的猫粮,问最多可以换多少的咖啡豆?

首先根据题意我们可以求出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);
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值