USACO 1.3 Mixing Milk (Greedy), USACO Mixing
USACO Mixing Milk
Simple greedy, read data, sort by unit price from small to large, and then buy from the cheapest until the purchase is enough.
/* ID: twd30651 PROG: milk LANG: C ++ */# include <iostream> # include <fstream> # include <stdlib. h> using namespace std; int N; int M; typedef struct node {int P; int A;} node; node data [5001]; int cmp (const void *, const void * B) // note that the cmp function must fully comply with the int (*) (const void *, const void *) FORM {node an = * (node *) a; node bn = * (node *) B; return. p> bn. p; // from small to large} int main (int argc, char * argv []) {freopen ("milk. in "," r ", stdin); freopen (" milk. out "," w ", stdout); scanf (" % d ", & N, & M); int I = 0; while (scanf ("% d", & data [I]. p, & data [I]. a) = 2) I ++; qsort (data, I, sizeof (node), cmp); // fast sorting int sum = 0; int count = 0; for (int j = 0; j <M; ++ j) {if (N-count> = data [j]. a) {count + = data [j]. a; sum + = data [j]. A * data [j]. p;} else {sum + = data [j]. P * (N-count); break;} printf ("% d \ n", sum); return 0;} Date: 2014-11-25T19: 34 + 0800 Author: kirchhoffOrg version 7.9.3f withEmacs version 24 Validate XHTML 1.0