1020. 月饼 (25)

原题: https://www.patest.cn/contests/pat-b-practise/1020

实现思路:
使用结构体, 这样库存和售价就能捆绑在一块, 然后对该结构体排序, 把最赚钱的月饼放在最前面.
之后循环遍历月饼结构体, 每次把总收益, 和总共卖出的月饼都记录下来, 这样的话, 如果不需要
取部分库存, 则判断需求和库存相等就OK, 如果需要取部分库存, 则我们的循环一定会在某个点大于
总需求, 这时候减去差值即可得到原本的总受益.

该题有2个坑:
坑1: 题目并没有说库存和售价是整数, 事实上如果把这两个数据错误的定义为整数, 则测试点2无法通过,
我自己就掉进这个坑里. 后经网友提醒, 方爬出来.
坑2: 月饼有可能不够卖. 但按照我们上面的实现, 该坑自动能规避.

本题有很多需要把整型转为浮点型的情况, 事实证明C语言自动类型转换, 就能完成任务.

完整C语言实现:

#include <stdio.h>
#include <stdlib.h>

/*
种类 需求
1库存量   2库存量   3库存量 ...
1总售价   2总售价   3总售价 ...
input:
3 20
18 15 10
75 72 45
output:
94.50
*/
struct mooncake {
    float number;
    float totalPrice;
};
typedef struct mooncake s_mk;

int compare (const void *a, const void *b);

int main () {
    int type;
    int demand;
    s_mk mk[1000];
    float now = 0;         // 当前实际卖出的月饼
    float allMoney = 0.0;  // 最大收益
    float temp;
    int i;

    scanf("%d %d", &type, &demand);
    // 为月饼结构体赋值
    for (i=0; i<type; i++) {
        scanf("%f", &(mk[i].number));
    }
    for (i=0; i<type; i++) {
        scanf("%f", &(mk[i].totalPrice));
    }

    // 把月饼按照 totalPrice / number, 从大到小排序
    // 即最赚钱的月饼放在最前, 也就是0号下标处
    qsort(mk, type, sizeof(s_mk), compare);
    for (i=0; i<type; i++) {
        // 第1种情况, 无需取部分库存, 刚好够
        if (now == demand) {
            break;
        }
        now += mk[i].number;
        allMoney += (float)(mk[i].totalPrice);
        // 第2种情况, 需要取部分库存
        if (now > demand) {
            temp = (float)(mk[i].totalPrice) / (float)(mk[i].number);
            allMoney = allMoney - ((float)(now - demand) * temp);
            break;
        }
    }
    printf("%.2f\n", allMoney);

    return 0;
}

int compare (const void *a, const void *b) {
    s_mk mk1 = *(s_mk*)a;
    s_mk mk2 = *(s_mk*)b;
    float value1 = (float)(mk1.totalPrice) / (float)(mk1.number);
    float value2 = (float)(mk2.totalPrice) / (float)(mk2.number);
    int res;

    if (value1 > value2) {
        res = -1;
    } else if (value1 < value2) {
        res = 1;
    } else {
        res = 0;
    }

    return res;
}

参考: http://blog.csdn.net/livecoldsun/article/details/36877345

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凯尔kyle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值