HDU 1009

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36496    Accepted Submission(s): 12021


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
 



题目大意: 一个老鼠有M pound食物, 然后需要获得 第i 行 的j[i] 食物 需要用 F[i] 来换 

解题方法:

            1、先找用最少的F[i] 换最多的J[i] 食物 及j[i]/F[i] 最大,这里做一个排序

             2、先把性价比最高的先换掉,然后再换其他的这里用一个循环解决, 循环终止条件就是全部换完

             3、这里要注意的是剩余换完了的  这个终止条件和终止状态很重要 ,在代码里已经注释了

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

struct fat
{
    double j;
    double f;
    double rate;
}s[1001];

bool cmp(fat s1, fat s2)
{
    return (s1.rate > s2.rate);
}
int  main()
{
    int M , N;
    int i;
    while(cin>>M>>N)
    {
        if(N == -1 && M == -1)
        {
            return 0;
        }
        for(i = 0; i < N; i++)
        {
            cin>>s[i].j>>s[i].f;
            s[i].rate = s[i].j/s[i].f;
        }
        sort(s, s+N, cmp);
        double sum = 0;
        for(i = 0; i < N; i++)
        {//如果可以换的先换掉且M的值刚好可以换完M小于
            if(s[i].f <= M)
            {
                M -= s[i].f;
                sum += s[i].j;
            }
            else
            {
                //换完之后还有剩余的不够换比如你最后只剩下1 但是结果数 4个可以换7 个你总不能直接拿7 个吧,因为不够4个
                sum += M*s[i].rate;
                //上面已经换完了要避免继续执行else里面的要写终止条件
                 M = 0;
                 break; //已经算完了循环终止
            }
        }
        printf("%.3lf\n", sum);

    }

    return 0;
}

贪心问题 。。。。。

wangxiaoming CSDN认证博客专家 架构 Spring Boot Redis
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付 19.89元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值