HDOJ-1009(cmp函数的一点问题)

C++语言 码拜 9年前 (2015-05-11) 1163次浏览 0个评论

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 <cstdio>
#include <algorithm>
using namespace std;

struct thing
{
    int f,j;
    double v;
}things[1000];

int N,M;
int cmp(thing a,thing b);

int main()
{
    int i,left;
    double count,temp;
    while(scanf("%d%d",&M,&N)!=EOF&&(M!=-1||N!=-1))
    {
        count=0;
        left=M;//每次输入都将left等于总共的食物亮,老鼠用于交换剩余的实物量
        for(i=0;i<N;i++)
        {
            scanf("%d%d",&things[i].j,&things[i].f);
            things[i].v=things[i].j/things[i].f;
        }
        sort(things,things+N,cmp);
        for(i=0;i<N;i++)
        {
            if(things[i].j<=left)
            {//如果剩下的食物比第i个猫要的食物还多
                count+=things[i].j;//获得i猫的全部豆子
                left-=things[i].f;//老鼠剩下的食物减少
                if(!left)break;
            }
            else
            {//剩下的食物比第i个猫要的食物少
                temp=left*things[i].v;
                count+=temp;
                break;
            }
        }
        printf("%.3lf\n",count);
    }
    return 0;
}
int cmp(thing a,thing b)
{
    return a.v>b.v;
}

大概就是这样,自己调试的时候也总是不知道错误到底处在哪里,感觉应该是cmp函数有点问题,但自己也找不出错误在哪,结果总是不对
求各位大神帮忙!

30分
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。
提醒:再牛×的老师也无法代替学生自己领悟和上厕所!
单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。
10分
cmp函数感觉是没有问题的
things[i].v=things[i].j/things[i].f;
这句话有问题,左边的值是double类型的,右边是两个整数相除,楼主应该知道C的除法得出的结果只保留整数的
things[i].v=1.0 * things[i].j/things[i].f; 这样强制转换为浮点数就没有问题
其它的没有看,楼主再试试吧
10分
if(things[i].f<=left)

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HDOJ-1009(cmp函数的一点问题)
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!