PAT (Basic Level) Practice (Chinese) 1020 Mooncake

 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

The sorting method of sort () function: sort (start, end position next to the comparison function) When the comparison function is not needed, the default is in increasing order, otherwise you need to define the comparison function yourself.

Guess you like

Origin www.cnblogs.com/Learn-Excel/p/12711184.html