我的思路是依据月饼单价进行排序,优先售出单价较高的月饼。要注意计算过程当中所有的数都要用实型,虽然样例给的重量都是整数。
#include<iostream>
#include<algorithm>
using namespace std;
struct mooncake{
float weight;
float price;
float per;
}M[1002];
bool cmp(mooncake a,mooncake b){
return a.per>b.per;
}
int main(){
int N;
float total;
scanf("%d %f",&N,&total);
int i;
for(i=0;i<N;i++)
scanf("%f",&M[i].weight);
for(i=0;i<N;i++)
scanf("%f",&M[i].price);
for(i=0;i<N;i++)
M[i].per=M[i].price*1.0/M[i].weight;
sort(M,M+N,cmp);
float sum=0;
i=0;
while(total>0 && i<N){
if(M[i].weight>=total){
sum+=total*M[i].per;
total=0;
}
else{
sum+=M[i].price;
total-=M[i].weight;
i+=1;
}
}
printf("%.2f",sum);
system("pause");
return 0;
}