FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.500
思路:本题关键在于按照交换比例由大到小的次序进行,可借助functor和标准库中的sort算法实现。下面给出我的C++实现代码:
#include <iostream> #include <vector> #include <algorithm> #include <cstdio> using namespace std; struct cell { double cat_food; double java_bean; double ratio() const { return java_bean / cat_food; } }; struct cell_compare { bool operator()( const cell & c1, const cell & c2 ) { return c1.ratio() > c2.ratio(); } }; int main() { double cat_food_w, num_cells; vector<cell> cells; cell c; double res = 0.0; cell_compare comp; while( /* cin >> cat_food_w >> num_cells */ scanf( "%lf %lf", &cat_food_w, &num_cells ) ) { if( cat_food_w == -1 || num_cells == -1 ) break; // read data for( int i = 0; i < num_cells; ++i ) { //cin >> c.java_bean >> c.cat_food; scanf( "%lf %lf", & c.java_bean, & c.cat_food ); cells.push_back( c ); } sort( cells.begin(), cells.end(), comp ); for( int i = 0; i < cells.size(); ++i ) { if( cat_food_w < cells[i].cat_food ) { res += cat_food_w * cells[i].ratio(); break; } else { cat_food_w -= cells[i].cat_food; res += cells[i].java_bean; } } printf( "%.3lf/n", res ); res = 0.0; cells.clear(); } return 0; }