FatMouse' Trade

#HDOJ1009

#主要想通过这道题来练习下结构体快排函数的使用

#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 37 24 35 220 325 1824 1515 10-1 -1
 

Sample Output
 
  
13.33331.500

#代码实现

#include<stdio.h>
#include<stdlib.h>

typedef struct fun_
{
    int J;
    int F;
}fun;

struct fun_ room[1000];

int comp(const void*a,const void *b)
{
    double A,B;
    A=(double)(((fun *)a)->J)/(((fun *)a)->F);
    B=(double)(((fun *)b)->J)/(((fun *)b)->F);
    return(A>B?1:-1);
}
int main()
{
    int M,N;
    while(scanf("%d%d",&M,&N)&&M!=-1)
    {
        double sum=0;      //最终获得的数量
        for(int i=0;i<N;i++)
            scanf("%d%d",&room[i].J,&room[i].F);
        qsort(room,N,sizeof(room[0]),comp);
        for(int i=N-1;i>=0;i--)
        {
            if(M>=room[i].F)   //能获得房间内全部的
            {
                sum+=room[i].J;
                M-=room[i].F;
            }

            else                //只能获得部分的(按百分比折算)
            {
                sum+=M*(double)room[i].J/room[i].F;
                break;
            }
        }
        printf("%.3f\n",sum);
    }
}
#代码中的double不能换成float,否则AC不了,float只有6-7位有效数字。

猜你喜欢

转载自blog.csdn.net/u014302425/article/details/80383745
今日推荐