注意一下,当需求大于所有库存的情况
#include <stdio.h>
#define MAX_N 1000 /* 月饼最大种类数 */
int N; /* 种类 */
float demand; /* 需求量 */
typedef struct mooncake{
float inventory; /* 库存量 */
float price; /* 单价 */
}mooncake;
struct mooncake nmc[MAX_N]; /* N种月饼的信息 n moon cake */
void read_info();
void print_income();
int getMaxP();
/******* 读入月饼种类数,需求量,以及读入N中月饼的库存和总售价,并计算单价 ********/
void read_info(){
int i;
scanf("%d %f", &N, &demand);
for(i = 0; i < N; ++i)
scanf("%f", &nmc[i].inventory);
for(i = 0; i < N; ++i){
scanf("%f", &nmc[i].price);
nmc[i].price /= nmc[i].inventory;
}
}
/******************************** 计算收益 ****************************************/
void print_income(){
float income = 0; /* 收益 */
int p_max; /* 最大单价月饼的下标 */
while(demand > 0){ /* 当需求量还没有满足 */
p_max = getMaxP(); /* 找一个单价最大的月饼 */
if(nmc[p_max].inventory == 0) /* 所有的库存都满足不了需求 售空了 */
break;
else if(demand >= nmc[p_max].inventory){/* 当前月饼种类的库存不能满足需求 */
income += nmc[p_max].inventory * nmc[p_max].price;
demand -= nmc[p_max].inventory;
nmc[p_max].inventory = 0;
}else{ /* 需求小于库存 */
income += demand * nmc[p_max].price;
break;
}
}
printf("%.2f", income); /* 输出收益 */
}
/***************************** 找最大单价的月饼 ************************************/
int getMaxP(){
int i, j;
float p;
p = j = 0;
for(i = 0; i < N; ++i)
if(nmc[i].inventory > 0 && nmc[i].price > p){
p = nmc[i].price;
j = i;
}
return j; /* 返回最大单价的位置 */
}
int main(){
read_info(); /* 读入信息 */
print_income(); /* 输出收益 */
return 0;
}