PAT (Basic Level) Practice (中文) 1020 月饼

 1 #include<stdio.h>
 2 #include<algorithm>
 3 using namespace std;
 4 const int MAXN=1001;
 5 struct kind{
 6     double num,price,p_price;
 7 };
 8 int d,n;
 9 struct kind a[MAXN];
10 
11 bool cmp(kind a,kind b);
12 double maxreturn(int d);
13 
14 int main(){
15     scanf("%d %d",&n,&d);
16     for(int i=0;i<n;i++) scanf("%lf",&a[i].num); 
17     for(int i=0;i<n;i++) scanf("%lf",&a[i].price);
18     for(int i=0;i<n;i++) a[i].p_price = a[i].price / a[i].num;
19     
20     sort(a,a+MAXN,cmp);
21     double mr = maxreturn(d);
22     printf("%.2f",mr);
23     return 0;
24 }
25 bool cmp(kind a,kind b){
26     return a.p_price > b.p_price;
27 }
28 double maxreturn(int d){
29     int i=0;
30     double mr=0.0;
31     while(d>0&&i<n){
32         if(a[i].num > d){
33             mr += d*a[i].p_price;
34             d = 0;
35             i++;
36         }else{
37             d -= a[i].num;
38             mr += a[i].price;
39             i++;
40         }
41     }
42     return mr;
43 }
View Code

sort()函数的排序方法: sort(起始,终止位置的下一个位置,比较函数) 比较函数不需要时,则默认按递增顺序进行,否则需要自行定义比较函数。

猜你喜欢

转载自www.cnblogs.com/Learn-Excel/p/12711184.html