PAT笔记
1070 Mooncake
Mooncake is a Chinese bakery product traditionally eaten during the Mid-Autumn Festival. Many types of fillings and crusts can be found in traditional mooncakes according to the region’s culture. Now given the inventory amounts and the prices of all kinds of the mooncakes, together with the maximum total demand of the market, you are supposed to tell the maximum profit that can be made.
Note: partial inventory storage can be taken. The sample shows the following situation: given three kinds of mooncakes with inventory amounts being 180, 150, and 100 thousand tons, and the prices being 7.5, 7.2, and 4.5 billion yuans. If the market demand can be at most 200 thousand tons, the best we can do is to sell 150 thousand tons of the second kind of mooncake, and 50 thousand tons of the third kind. Hence the total profit is 7.2 + 4.5/2 = 9.45 (billion yuans).
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive integers N (≤1000), the number of different kinds of mooncakes, and D (≤500 thousand tons), the maximum total demand of the market. Then the second line gives the positive inventory amounts (in thousand tons), and the third line gives the positive prices (in billion yuans) of N kinds of mooncakes. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the maximum profit (in billion yuans) in one line, accurate up to 2 decimal places.
贪心思想,对月饼的价值排序,优先选择价值大的月饼。
创建月饼对象,并且分别有数量,价格,价值三个属性,然后根据价值按从大到小排序。
Java中list排序中,只能返回int值,对浮点型不能排序。这里选择重写CompareTo 方法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main{
private static class Cake implements Comparable<Cake>{
double amount;
double price;
double value;
public Cake(double amount,double price,double value){
this.amount=amount;
this.price=price;
this.value=value;
}
@Override
public int compareTo(Cake cake){
return cake.value>value?1:-1;
}
}
public static void main(String[]args) throws IOException {
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String s[]=input.readLine().split(" ");
int n=Integer.valueOf(s[0]);
double sum=Double.valueOf(s[1]);
List<Cake> list=new ArrayList<>();
String s1[]=input.readLine().split(" "),s2[]=input.readLine().split(" ");
for(int i=0;i<n;i++){
double amount=Double.valueOf(s1[i]);
double price=Double.valueOf(s2[i]);
double value=price/amount;
Cake cake=new Cake(amount,price,value);
list.add(cake);
}
Collections.sort(list);
double res=0;
for(int i=0;i<n;i++){
if(sum-list.get(i).amount>=0){
res+=list.get(i).price;
sum-=list.get(i).amount;
}else{
res+=list.get(i).value*sum;
break;
}
}
System.out.printf("%.2f",res);
}
}