zoukankan      html  css  js  c++  java
  • PAT B1020

    PAT B1020


    解决思路 :贪心法,每次选取单价最高的月饼。

    先上一个自己错误的解法

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    
    double num[1010];
    double price[1005];
    double ans = 0;
    
    int main() {
        int n, d;
        scanf("%d%d", &n, &d);
        for (int i = 0; i < n; i++) {
            scanf("%lf", &num[i]);
        }
        for (int i = 0; i < n; i++) {
            scanf("%lf", &price[i]);
            price[i] = price[i] / num[i];
        }
        sort(price, price + n);
    
        for (int i = n - 1; i >= 0; i--) {
            while (num[i] > 0 && d > 0) {
                ans += price[i];
                num[i]--;
                d--;
            }
        }
    
    
        printf("%.2f", ans);
        return 0;
    }
    

    然后是题解

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    
    struct mooncake {
        double store; //库存
        double sell;   //总价
        double price;  /单价
    }cake[1010];
    
    bool cmp(mooncake a, mooncake b) {
        return a.price > b.price;
    }
    
    int main() {
       int n;
       double D;
       scanf("%d%lf", &n, &D);
       for (int i = 0; i < n; i++) {
        scanf("%lf", &cake[i].store);
       }
       for (int i = 0; i < n; i++) {
        scanf("%lf", &cake[i].sell);
        cake[i].price = cake[i].sell / cake[i].store;
       }
       sort(cake, cake + n, cmp);
       double ans = 0;
       for (int i = 0; i < n; i++) {   
        if (cake[i].store <= D) {    //如果需求高于月饼的库存
            D -= cake[i].store;    //先把第i种全部卖出
            ans += cake[i].sell;
        } else {                 //库存高于需求
            ans += cake[i].price * D;   //只售出该种月饼,数量为需求量,然后break;
            break;
        }
       }
       printf("%.2f", ans);
       return 0;
    }
    
  • 相关阅读:
    css面试题目
    5. React-Router05 BrowserRouter 和hashrouter
    5. React-Router03 withRouter
    5. React-Router01
    CVE-2019-0708—微软RDP远程桌面代码执行漏洞复现
    正则表达式学习汇总
    CTF---PHP安全考题
    快速搭建主动诱导型开源蜜罐框架系统--hfish
    python--爬取网页存在某字符
    Linux 实用指令之查看端口开启情况
  • 原文地址:https://www.cnblogs.com/Kirarrr/p/10339815.html
Copyright © 2011-2022 走看看