/* ID:tianlin2 PROG:milk LANG:C++ */ #include <iostream> #include <cstdlib> #include <fstream> using namespace std; typedef struct milk milk; struct milk{ int mon; int wei; }; //最大农民数 milk m[5000]; int moncmp(const void *va,const void *vb) { milk *a,*b; a=(milk*)va; b=(milk*)vb; if(a->mon>b->mon) return 1; if(a->mon<b->mon) return -1; return 0; } int main() { ofstream fout("milk.out"); ifstream fin("milk.in"); int we,cfar,cmon=0,cwei=0; fin>>we>>cfar; for(int i=0;i!=cfar;++i) fin>>m[i].mon>>m[i].wei; qsort(m,sizeof(milk),moncmp); for(int i=0;i!=cfar;++i) { cwei+=m[i].wei; if(cwei<=we) cmon+=m[i].wei*m[i].mon; //考虑了多出的情况 else { cmon=cmon+m[i].wei*m[i].mon-(cwei-we)*m[i].mon; cwei=we; } if(cwei==we) break; } fout<<cmon<<endl; //system("pause"); return 0; }
利用了qsort先把m按照单价的大小升序排列,接下来就好办了!从最低的价格开始算起!
官方给出的优秀算法:
#include <fstream> #define MAXPRICE 1001 using namespace std; int main() { ifstream fin ("milk.in"); ofstream fout ("milk.out"); unsigned int i,needed,price,paid,farmers,amount,milk[MAXPRICE][2]; paid = 0; fin>>needed>>farmers; for(i = 0;i<farmers;i++){ fin>>price>>amount; milk[price][0] += amount; } for(i = 0; i<MAXPRICE && needed;i++){ if(needed> = milk[i][0]) { needed -= milk[i][0]; paid += milk[i][0] * i; } //判断此价格点是否有奶供应 else if(milk[i][0]>0) { paid += i*needed; needed = 0; } } fout << paid << endl; return 0; }
很巧妙的省去了排序,直接定义一个价格i,历遍所有价格,看此价格点处是否有奶供应!