码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1009 贪心入门

时间:2016-03-20 01:57:55      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

Mycode:

compile error,i don‘t know why?

#include <iostream>
#include<algorithm>
#include<cstdio>
#define maxn 10005
using namespace std;
struct room
{
    int j;
    int f;
    double val;
};
struct room r[3001];
bool compare(struct room a,struct room b)
{
  return a.val > b.val;
}
int main()
{
    double n,m;
    while(cin >> m >> n)
    {
        if(m == -1&&n == -1)
            break;
        for(int i = 0;i < n;i ++)
        {
            cin >> r[i].j;
            cin >> r[i].f;
            r[i].val = (double)r[i].j/r[i].f;
        }
        struct room *p = &p[0];
        sort(p,p+n,compare);
        double ans = 0;
        for(int i = 0;i < n&&m > 0;i ++)
        {
            if(m > r[i].f){
                ans += r[i].j;
                m -= r[i].f;
            }
            else{
                ans += r[i].j * (m/r[i].f);
                m = 0;
            }
        }
        printf("%.3f\n",ans);
    }
    return 0;
}

Correct code:

#include<stdio.h>
#include<algorithm>
using namespace std;
struct Trade
{
    int j,f;
    double percent;
}mouse[3001];
bool cmp(Trade a,Trade b)
{
    return a.percent>b.percent;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&m,&n)!=EOF&&(n!=-1||m!=-1))
    {
        int i;

        for(i=0;i<n;i++)
        {
            scanf("%d%d",&mouse[i].j,&mouse[i].f);
            mouse[i].percent=(double)mouse[i].j/mouse[i].f;
        }
        sort(mouse,mouse+n,cmp);
        double sum=0;
        for(i=0;i<n;i++)
        {
            if(m>mouse[i].f)
                 {
                     sum+=mouse[i].j;
                     m-=mouse[i].f;
                 }
            else
                //break;
            {
                sum+=mouse[i].percent*m;
                m=0;
                break;
            }


        }

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

    }
    return 0;
}

 

hdu 1009 贪心入门

标签:

原文地址:http://www.cnblogs.com/zhangjialu2015/p/5296840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!