★Mixing Milk 混合牛奶
牛奶包装是一个如此低利润的生意,所以尽可能低的控制初级产品(牛奶)的价格变的十分重要. 请帮助快乐的牛奶制造者(Merry Milk Makers)以可能的最廉价的方式取得他们所需的牛奶. 快乐的牛奶制造公司从一些农民那购买牛奶,每个农民卖给牛奶制造公司的价格不一定相同. 而且,如一只母牛一天只能生产一定量的牛奶,农民每一天只有一定量的牛奶可以卖.Ai(0 <= Ai <= 2,000,000)是农民 i 一天能卖给快乐的牛奶制造者的牛奶数量.
public class P1 { //构造堆 List<milk> heap = new ArrayList<milk>(); /** * 建立堆 */ public void buildHead(){ for(int i = heap.size()/2 -1; i >= 0 ; i--){ heapify(i); } } /** * 获取堆顶元素的值 */ public milk get(){ if(heap.isEmpty()) return null; return heap.get(0); } /** * 删除堆顶元素 */ public milk delete(){ milk result = heap.get(0); heap.set(0,heap.get(heap.size() - 1)); heap.remove(heap.size() -1); if(heap.isEmpty()){ return result; }else{ heapify(0); return result; } } /** * 使删除堆顶元素的堆重新成为堆 * 使第i个元素下降 */ public void heapify(int i){ //孩子结点为2*i 和 2*i+1 milk e = heap.get(i); Double element = heap.get(i).price; int child,j; for(j = i ; j < heap.size() ; j = child){ child = 2 * j + 1; if((child + 1) < heap.size() && heap.get(child).price > heap.get(child + 1).price){ child++; } if(child >= heap.size()){ break; } if(element > heap.get(child).price){ heap.set(j,heap.get(child)); }else{ break; } } heap.set(j, e); } public static void main(String[] args){ P1 p = new P1(); double money = 0; Scanner sc = new Scanner(System.in); int total = sc.nextInt(); int n = sc.nextInt(); for(int i = 0; i < n; i++){ milk m = new milk(); m.price = sc.nextDouble(); m.count = sc.nextInt(); p.heap.add(m); } p.buildHead(); while(total > 0){ milk temp = p.delete(); if(total >= temp.count){ total = total - temp.count; money = money + temp.count * temp.price; }else{ money = money + total * temp.price; total = 0; } } System.out.println(money); } } class milk{ double price; int count; }