HDU 1009 Fatmouse's trade

贪心+排序

#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace
std;
int
M,N;
struct
wareroom
{

    int
Javabean;
    int
catfood;
    double
balance;
};

wareroom room[100000];
int
cmp(const void* a,const void* b)
{

    wareroom c=*(wareroom*)a;
    wareroom d=*(wareroom*)b;
    double
temp=d.balance-c.balance;
    if
(temp>0)return 1;
    else if
(fabs(temp)<0.00001)return 0;
    else return
-1;
}

int
main()
{

    while
(scanf("%d %d",&M,&N)!=EOF)
    {

        if
(M==-1&& N==-1)break;
        int
i;
        double
sum=0;
        for
(i=0;i<N;i++)
        {

            scanf("%d %d",&room[i].Javabean,&room[i].catfood);
            room[i].balance=((double)room[i].Javabean)/((double)room[i].catfood);
        }

        qsort(room,N,sizeof(room[0]),cmp);
        /*for(i=0;i<N;i++)
        {
            printf("%.3lf  ",room[i].balance);
        }*/

        for
(i=0;i<N&&M>0;i++)
        {

            if
(M>=room[i].catfood)
            {

                sum+=room[i].Javabean;
                M-=room[i].catfood;
            }
else
            {

                sum+=((double)M)/((double)room[i].catfood)*room[i].Javabean;
                break
;
            }
        }

        printf("%.3lf\n",sum);
    }

    return
0;
}

你可能感兴趣的:(HDU)