原题
https://pintia.cn/problem-sets/994805260223102976/problems/994805301562163200
代码
java代码超时,c代码通过(c解法点击跳转)
循环+每次把最大值遍历比较出来(较费时)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int D = scanner.nextInt();
float profit=0;
float stock[]=new float[1000],prices[]=new float[1000];
for (int i=0;i<N;i++) stock[i]=scanner.nextFloat();
for (int i=0;i<N;i++) prices[i]=scanner.nextFloat();
while (D>0){
int max=0;
for (int i=0;i<N;i++){
if ((prices[i]/stock[i])>(prices[max]/stock[max])){
max=i;
}
}
if (D>stock[max]){
profit+=prices[max];
D-=stock[max];
prices[max]=0;//把最大的单价的位置清零,下一轮不会选到它为最大值
}else {
profit+=D*prices[max]/stock[max];//注意这里的+号,最后一次比较
D=0;
}
}
System.out.printf("%.2f",profit);
}
}
先排序+再填入。使用类来存储各种类的月饼(c用结构体)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int D = scanner.nextInt();
float protit=0;
ArrayList<MoonCake> list = new ArrayList<>();
for (int i=0;i<N;i++) {//填入库存
MoonCake moonCake = new MoonCake();
moonCake.setStock(scanner.nextFloat());
list.add(moonCake);
}
for (int i=0;i<N;i++) {//填入总价与计算单价
list.get(i).setPrice(scanner.nextFloat());
list.get(i).setUnitPrice(list.get(i).getPrice()/list.get(i).getStock());
}
Collections.sort(list);//排序
for (int i=0;i<N;i++){//按顺序填入
if (list.get(i).getStock()<D){//小于库存
protit+=list.get(i).getStock()*list.get(i).getUnitPrice();
D-=list.get(i).getStock();
}else {
protit+=D*list.get(i).getUnitPrice();//最后一次
break;
}
}
System.out.printf("%.2f",protit);
}
}
class MoonCake implements Comparable<MoonCake>{
private float stock;
private float price;
private float unitPrice;
@Override
public int compareTo(MoonCake o) {
return -Double.compare(unitPrice,o.unitPrice);//按从大到小逆向排序
}
public float getStock() {
return stock;
}
public void setStock(float stock) {
this.stock = stock;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(float unitPrice) {
this.unitPrice = unitPrice;
}
}