Monday, April 23, 2012

1.3 Problem 76: Mixing Milk

Only 2 failures due to the final cost costing the product of the available number and required, not the price and required number.

I didn't use qsort for it like the analysis. It looks like my solution is similar to the good exemplars.
This one is easy, as two farmers selling the same same price could be combined into one "provider" selling both amounts at the same price each. Since this is a greedy match, take as many as possible from the lowest price, and move on to the next expensive, ..., until there's no more.
/*
ID: victor4
PROG: milk
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#define MAXCOSTS 1001

int main() {
 ofstream fout ("milk.out");
 ifstream fin ("milk.in");
 
 int req, farmers;
 fin >> req >> farmers;
 
 int available[MAXCOSTS] = {0};
 for(int i = 0; i < farmers; ++i){
  int price, amt;
  fin >> price >> amt;
  available[price % MAXCOSTS] += amt;
 }
 
 int cost = 0;
 for(int i = 0; i < MAXCOSTS; ++i){
  if(available[i]){
   if(available[i] >= req){
    cost += i * req;
    break;
   }
   else{
    cost += i * available[i];
    req -= available[i];
   }
  }
 }
 
 fout << cost << endl;
 return 0;
}

No comments:

Post a Comment