[Java] Mixing Milk

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: milk
*/
import java.io.*;
import java.util.*;

class Farmer implements Comparable<Farmer> {
     
		
	private int price;
	private int amount;
	Farmer(int price, int amount) {
     
		this.price = price;
		this.amount = amount;
	}
	public int getPrice() {
     
		return price;
	}
	public int getAmount() {
     
		return amount;
	}
	public int compareTo(Farmer that) {
     
		return this.price - that.price;
	}
	public String toString() {
     
		return "(" + price + " " + amount + ")";
	}
}

public class milk {
     

	public milk() throws IOException {
     
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("milk.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk.out")));

		// Use StringTokenizer vs. readLine/split -- lots faster
		StringTokenizer st = new StringTokenizer(f.readLine());
		// N, (0 <= N <= 2,000,000) is the amount of milk that Merry Milk Makers wants per day.
	    int N = Integer.parseInt(st.nextToken());
	    // M, (0 <= M <= 5,000) is the number of farmers that they may buy from
	    int M = Integer.parseInt(st.nextToken());    // second integer
	    
	    Farmer[] farmers = new Farmer[M];
	    for (int i = 0; i < M; i++) {
     
	    	st = new StringTokenizer(f.readLine());
	    	int pi = Integer.parseInt(st.nextToken());
	    	int ai = Integer.parseInt(st.nextToken());
	    	farmers[i] = new Farmer(pi, ai);
	    }
	    Arrays.sort(farmers);

	    int cost = 0;
	    for (int i = 0; i < M; i++) {
     
	    	if (N > farmers[i].getAmount()) {
     
	    		cost += farmers[i].getAmount() * farmers[i].getPrice();
	    		N -= farmers[i].getAmount();
	    	}
	    	else {
     
	    		cost += N * farmers[i].getPrice();
	    		break;
	    	}
	    }
	    out.println(cost);
	    out.close();                                  // close the output file
	}
	
	public static void main (String [] args) throws IOException {
     
		new milk();
	}
}

你可能感兴趣的:(USACO)