【HDU 1009】【贪心】FatMouse' Trade

  题目的大意就是给你两个数字,一个表示老鼠有几斤的猫粮,然后又几个房间,每个房间有多少鼠粮,这些鼠粮价值多少猫粮。鼠粮可以拆开,所以是个贪心问题,我们求出鼠粮的单价然后排序就可以了。

 

#include "stdio.h"
#include"algorithm"
using namespace std;
struct ck
{
    double space;
    double bean;
    double price;
}room[100000];
int cmp(ck a,ck b)
{
    return a.price>b.price;
}
int main()
{
    int n,m,i;
    double sum;
    while (~scanf("%d %d",&m,&n)&&n!=-1&&m!=-1)
    {
        sum=0;
        for (i=0; i<n; i++) 
        {
            scanf("%lf %lf",&room[i].bean,&room[i].space);
            room[i].price=room[i].bean/room[i].space;
        }
        sort(room,room+n,cmp);
        for (i=0; i<n; i++)
        {
            
           // printf("%.1lf %.3lf\n",room[i].price,sum);
            if(room[i].space>=m)
            {
                sum+=room[i].price*m;
                break;
            }
            else
            {
                sum+=room[i].bean;
                m-=room[i].space;
            }
        }
        printf("%.3lf\n",sum);
    }
}

你可能感兴趣的:(c,水题)