Problem Description
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.
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
大致题意:
胖老鼠有 M 的猫粮,告诉你好多房间,里面可以用猫粮换吃的,以及换的方式。问你最多换多少。
解题思路:
贪心,按比率排个序取最划算就好。
1 #include <iostream>
2 #include <algorithm>
3 #include <cstdio>
4 using namespace std;
5 struct P{
6 int f,j;
7 double r;
8 }s[1005];
9 bool cmp(P x,P y){
10 return x.r>y.r;
11 }
12 int main(){
13 int m,n;
14 while(cin>>m>>n,n+m!=-2){
15 for(int i=0;i<n;i++){
16 cin>>s[i].f>>s[i].j;
17 s[i].r=1.0*s[i].f/s[i].j;
18 }
19 sort(s,s+n,cmp);
20 int j=0;
21 double ans=0;
22 while(m>0&&j<n){
23 if(m>=s[j].j){
24 m-=s[j].j;
25 ans+=s[j].f;
26 }
27 else{
28 ans+=1.0*m/s[j].j*s[j].f;
29 m=0;
30 }
31 j++;
32 }
33 printf("%.3lf
",ans);
34 } return 0;
35 }