zoukankan      html  css  js  c++  java
  • PTA 乙级 1020 月饼 (25分) C++

     利用sort函数对平均数进行排序

    C++

     1 #include <iostream>
     2 #include <algorithm>
     3 
     4 using namespace std;
     5 
     6 struct Goods {                    //货物结构体(库存,总售价,单价)
     7     float mass, price, arg;
     8 }goods[1000];
     9 
    10 bool cmp(Goods g1, Goods g2) {    //sort函数中返回bool的比较函数
    11     return g1.arg > g2.arg;
    12 }
    13 
    14 int main() {
    15     int n = 0, d = 0;
    16     float max = 0.0;
    17     cin >> n >> d;                
    18     for (int i = 0; i < n; i++) 
    19         cin >> goods[i].mass;
    20     for (int i = 0; i < n; i++) {
    21         cin >> goods[i].price;
    22         goods[i].arg = goods[i].price / goods[i].mass; //单价计算
    23     }
    24     sort(goods, goods+n,cmp);        //利用sort函数,按单价从大到小排序
    25     for (int i = 0; i < n; i++) {
    26         if (d >= goods[i].mass) {    //判断是否超过最大需求量
    27             d -= goods[i].mass;        //d剩余部分
    28             max += goods[i].price;
    29         }
    30         else {
    31             max += goods[i].arg * d;    //临界部分,由d剩余部分*单价计算得出
    32             break;
    33         }
    34     }
    35     printf("%.2f", max);
    36     return 0;
    37 }

  • 相关阅读:
    idea 快捷键
    上传代码
    maven 打包
    mysql 通过测试'for update',深入了解行锁、表锁、索引
    mysql中,手动提交事务
    java 发送邮件
    zk脑裂
    malloc,free和new,delete之间的区别
    sizeof和strlen区别
    字符串常量问题
  • 原文地址:https://www.cnblogs.com/SCP-514/p/13258063.html
Copyright © 2011-2022 走看看