ZZULIOJ 1187: 棒棒糖(结构体专题),Java
题目描述
新年快到了,计算机学院新年晚会正在筹备中,今年有一个新创意:来参加晚会的所有学生都有礼物(一根棒棒糖)。老师把买棒棒糖的任务交给小明了,并指定了要买的棒棒糖的品牌和品种。俗话说得好,货比三家不吃亏。小明来到了商店,看了各个店铺里这种棒棒糖的价格,不仅如此,他还记住了每个店铺的存货量。已知小明打算购买n根棒棒糖,问他最少要花多少钱?
输入
第一行输入一个整数n,表示要购买的棒棒糖数量;第二行是一个整数m(1<=m<=10),表示明明考察过的店铺的数量;接下来m行,每行两个数,表示该店铺中棒棒糖的价格和数量,价格为一实数(最多两位小数),数量为一整数。
输出
输出一个实数,保留两位小数,表示最小费用。
样例输入 Copy
java
100
4
0.5 50
0.33 30
1 80
0.6 40
样例输出 Copy
java
46.90
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class CandyShop implements Comparable<CandyShop> {
double price;
int quantity;
public CandyShop(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public int compareTo(CandyShop o) {
return Double.compare(this.price, o.price);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<CandyShop> shops = new ArrayList<>();
for (int i = 0; i < m; i++) {
double price = sc.nextDouble();
int quantity = sc.nextInt();
shops.add(new CandyShop(price, quantity));
}
Collections.sort(shops);
double minCost = 0.0;
int remainingCandy = n;
for (CandyShop shop : shops) {
int buyQuantity = Math.min(remainingCandy, shop.quantity);
minCost += buyQuantity * shop.price;
remainingCandy -= buyQuantity;
if (remainingCandy == 0) {
break;
}
}
System.out.printf("%.2f\n", minCost);
}
}