理解:
要算出最大收益必须计算出每种月饼的单价,通过比较单价进行由大到小的逆序排序,对排序后的数组计算最大收益。建议不要使用Scanner输入,会超时几个。
代码1:自定义类
import java.io.*; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s1 = br.readLine().split(" "); int n=Integer.parseInt(s1[0]); double d=Double.parseDouble(s1[1]); mooncake[] mk=new mooncake[n]; String[] s2 = br.readLine().split(" "); String[] s3 = br.readLine().split(" "); double max=0; for(int i=0;i<n;i++) { double x=Double.parseDouble(s2[i]); double y=Double.parseDouble(s3[i]); mk[i]=new mooncake(x,y,y/x); } Arrays.sort(mk); //使用Comparable 接口,才能用Arrays.sort()来给自定义的数据数组逆序排序 for(int i=0;i<n;i++) { //System.out.println(mk[i].inventory); if(d>=mk[i].inventory) { max=max+mk[i].price; d=d-mk[i].inventory; } else if(d<mk[i].inventory) { max=max+mk[i].unitprice*d; break; } else if(d<=0) break; } System.out.printf("%.2f",max); } } class mooncake implements Comparable<mooncake>{ public double price; public double unitprice; public double inventory; public mooncake(double i,double p,double u) { inventory=i; price=p; unitprice=u; } public int compareTo(mooncake a) { return unitprice>a.unitprice ?-1:1; //个人理解:另外一个和这个相比,如果比这个小,返回-1,排在这个的后面 } }
代码2:用三个double数组记录
import java.io.*; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s1 = br.readLine().split(" "); int n=Integer.parseInt(s1[0]); double d=Double.parseDouble(s1[1]); String[] s2 = br.readLine().split(" "); String[] s3 = br.readLine().split(" "); double[] inventory=new double[n];//库存清单 double[] price = new double[n];//价格 double[] unitPrice=new double[n]; double maxreturn=0; for(int i=0;i<n;i++) { inventory[i]=Double.parseDouble(s2[i]); } for(int i=0;i<n;i++) { price[i]=Double.parseDouble(s3[i]); unitPrice[i]=price[i]/inventory[i]; } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { double tempi=0; double tempp=0; if(unitPrice[i]>unitPrice[j]) { tempi=inventory[i]; inventory[i]=inventory[j]; inventory[j]=tempi; tempp=price[i]; price[i]=price[j]; price[j]=tempp; } } } Arrays.sort(unitPrice);//升序,由小到大 for(int i=n-1;i>-1;i--) { //System.out.println(inventory[i]+" "+unitPrice[i]*inventory[i]+" "+price[i]); if(d>=inventory[i]) { maxreturn=maxreturn+price[i]; d=d-inventory[i]; } else if(d<inventory[i]) { maxreturn=maxreturn+unitPrice[i]*d;//这里if的逻辑之前有错误,不一定必须创建一个类来做 break; } else if(d<=0) break; } System.out.printf("%.2f",maxreturn); } }
学习:
关于MyComparator 继承 Comparator接口并重写 compare 方法,看Arrays.sort()的三种用法
类继承 Comparable 接口并重写 compareTo 方法,看PAT 1020 月饼 (25分)(Java)