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 }

  • 相关阅读:
    select,radio,checkBox,获取/设置选中项的值和文本
    前端自学习网站
    ECMAScript 6
    常见几种浏览器兼容性问题
    HTML+CSS
    高级程序设计JavaScript
    年龄显示0.5岁
    编译原理
    underscore.js常用的API
    python中的字符串
  • 原文地址:https://www.cnblogs.com/SCP-514/p/13258063.html
Copyright © 2011-2022 走看看