利用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 }