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

posted @ 2017-10-22 20:16  阿胜4K  阅读(315)  评论(0编辑  收藏  举报