HDU-ACM课堂作业 FATMOU'S TRADE

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 485   Accepted Submission(s) : 122
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.
 

 

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
 
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include <iomanip>
#include<math.h>
using namespace std;
#define MAXN 1024
// M  catfood
// N room
struct room
{
    double javabeans;
    double food;
    double rate;
};

int cmp(room a, room b)
{
    return a.rate>b.rate;
}

int main()
{
    int n;
    double m;
    room arr[MAXN];
    while(cin>>m>>n)
    {
        if(m==-1&&n==-1)
            return 0;
        double sum=0;
        for(int i=0;i<n;i++)
        {
            double x, y;
            cin>>x>>y;
            arr[i].javabeans=x;
            arr[i].food=y;
            arr[i].rate=x/y;
        }
        sort(arr, arr+n, cmp);
        for(int i=0;i<n && m>0;i++)
        {
         //   cout<<m<<endl;
            if(m-arr[i].food>0.001)
            {
                m-=arr[i].food;
                sum+=arr[i].javabeans;
            }
            else
            {
                sum+=m*arr[i].rate;
                m=0;
            }
        }
        printf("%.3lf\n", sum);
    }
    return 0;
}

之前一直WA,有几个错误要注意

1.M 应该都用double类型

2. 开的数组大小问题

3. 最后用for(int i=0;i<n && m>0;i++)比较好,一开始用的while(m)一直WA,因为测试数据里可能有超过n的数据

posted @ 2018-12-20 16:11  图袋鼠  阅读(98)  评论(0编辑  收藏  举报