FatMouse' Trade - 九度教程第21题

本篇博客探讨了FatMouse如何利用有限资源进行最优交易的问题。通过分析不同房间内JavaBeans的价格和数量,采用贪心策略实现最大收益。文章提供了一种算法解决方案,包括数据结构设计、排序和计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FatMouse’ Trade - 九度教程第21题

题目

时间限制:1 秒 内存限制:128 兆 特殊判题:否
题目描述:
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.
样例输入:
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
样例输出:
13.333
31.500

题目大意如下:有M元钱,N种物品;每种物品有J[i]磅,价值F[i]元。可以使用0到F[i]的任意价格购买相应磅的物品,例如使用 F[i]* a% 元,可以购买J[i]* a% 磅物品。要求输出用M元钱最多能买到多少磅物品。
采用贪心策略,每次都买剩余物品中性价比(即重量价格比)最高的物品,直到该物品被买完或者钱耗尽。

#include <stdio.h>
#include <algorithm>
using namespace std;

struct Bean{
    double weight;
    double value;
    double rate;
    bool operator < (const Bean &B) const {
        return rate > B.rate;
    }
};

int main()
{
    double M;
    int N;
    while(scanf("%lf%d",&M,&N)!=EOF && M!=-1 &&N!=-1){
        Bean bean[N];
        for(int i=0;i<N;i++){
            scanf("%lf%lf",&bean[i].weight,&bean[i].value);
            bean[i].rate=bean[i].weight/bean[i].value;//单位价值能够购买的商品重量
        }
        sort(bean,bean+N);
        for(int i=0;i<N;i++){
            printf("%lf %lf\n",bean[i].weight,bean[i].value);
        }

        double res=0;
        for(int i=0;i<N;i++){
            if(M-bean[i].value >=0){
                res+=bean[i].weight;
                M-=bean[i].value;
                printf("buy %lf %lf\n",bean[i].weight,bean[i].value);
                if(M<=0)break;
            }else{
                res+=(M/bean[i].value)*bean[i].weight;
                printf("buy %lf %lf\n",(M/bean[i].value)*bean[i].weight,M);
                break;
            }
        }
        printf("%.3lf\n",res);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值