FatMouse' Trade
阿新 • • 發佈:2018-02-20
number homework 1.5 gre with span 使用 lin amp 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.
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.
InputThe 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.
OutputFor 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
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 using namespace std; 5 struct kang 6 { 7 double a, b; 8 }; 9 bool cmp(const kang&a, const kang&b) 10 { 11 return 1.0*a.a / a.b > 1.0*b.a / b.b; 12 } 13 int main() 14 { 15 kang k[10000]; 16 int m, n; 17 18 while (cin >> m >> n,n == -1 && m == -1) 19 { 20 double sum=0; 21 for (int i = 0; i < n; i++) 22 cin >> k[i].a >> k[i].b; 23 sort(k, k + n , cmp);24 for (int i = 0; i < n&&m != 0; i++) 25 { 26 if (m - k[i].b >= 0) 27 { 28 sum += k[i].a; 29 m -= k[i].b; 30 } 31 else 32 { 33 sum += m * 1.0*k[i].a / k[i].b; 34 m = 0; 35 } 36 } 37 printf("%.3f\n", sum); 38 } 39 return 0; 40 }
簡單的貪心題,自定義一個cmp就看解決,不過在用sort時註意區間為左閉右開;
也可以使用符號重載:
bool operator < (const kang & a, const kang & b)
{
return a.a / a.b > b.a / b.b;
}(已測試)
FatMouse' Trade